Given a root node root of a binary tree, return its in-order traversal. 【LeetCode Hot 100】

Question 94 of the Hottest Questions 100

Method 1, recursive method:

First we have to know what is an in-order traversal of a binary tree: left subtree node - root node - right subtree node. That is, when a node is encountered, the left subtree of the node is first traversed, and after the traversal is completed, the root node is reached, and finally the right subtree is reached. As shown below:

Then the result of in-order traversal of this binary tree is: 4 2 8 6 5 7 1 3;

Through this idea, we can understand that when we need to traverse a whole tree in inorder, we have to traverse its left subtree first, and to traverse its left subtree, we need to traverse the left subtree of its left subtree first. subtrees, etc. So we can use recursion to solve this problem. The specific code is:

class Solution {

    List<Integer> answer = new ArrayList<>();
    public List<Integer> inorderTraversal(TreeNode root) {
        inorder(root);
        return answer;
    }

    public void inorder(TreeNode root){
        if(root == null){
            return;
        }
        inorder(root.left);
        answer.add(root.val);
        inorder(root.right);
    }
}

Method two, iterative method:

When using the iterative method, because recursion is not possible, when traversing nodes, each traversed node needs to be stored. Here we use the stack to assist in solving the problem. The specific code is:

class Solution {
     public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> answer = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;

        while(cur != null || !stack.isEmpty()){
            while(cur != null){
            stack.push(cur);
            cur = cur.left;
            }
            TreeNode ret =  stack.pop();
            answer.add(ret.val);
            cur = ret.right;
        }
        return answer;
    }
}

Guess you like

Origin blog.csdn.net/weixin_56960711/article/details/123334931