【LeetCode】94. Inorder traversal of binary tree

topic

Given the root of a binary tree  root , return  its  inorder  traversal  .

Example 1:

Input: root = [1,null,2,3]
 Output: [1,3,2]

Example 2:

Input: root = []
 Output: []

Example 3:

Input: root = [1]
 Output: [1]

hint:

  • The number of nodes in the tree is  [0, 100] within the range
  • -100 <= Node.val <= 100

answer

source code

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        dfs(res, root);

        return res;
    }

    public void dfs(List<Integer> res, TreeNode root) {
        if (root == null) {
            return;
        }

        dfs(res, root.left);
        res.add(root.val);
        dfs(res, root.right);
    }
}

Summarize

This question is very simple to use recursive backtracking, as long as you remember that the in-order traversal is left, middle and right, then the operation of adding elements is placed in the middle of the left and right recursion.

Guess you like

Origin blog.csdn.net/qq_57438473/article/details/131948230