94. Binary Tree Inorder Traversal

Given a binary tree, return the inorder traversal of its nodes' values.

For example:
Given binary tree [1,null,2,3],

   1
    \
     2
    /
   3

return [1,3,2].
Note: Recursive solution is trivial, could you do it iteratively?

一刷
题解:
树的遍历复习: Pre-Order(root, left, right), In-Order(left, root, right), Post-Order(left, right, root)。总结,pre, in, post都是针对root的相对位置来说的。

递归很简单:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List inorderTraversal(TreeNode root) {
        List res = new ArrayList<>();
        inorderTraversal(res, root);
        return res;
    }
    
    private void inorderTraversal(List res, TreeNode root){
        if(root==null) return;
        inorderTraversal(res, root.left);
        res.add(root.val);
        inorderTraversal(res, root.right);
    }
}

尝试iteratively,栈

public class Solution {
    public List inorderTraversal(TreeNode root) {
        List res = new ArrayList<>();
        Stack stack = new Stack<>();
        TreeNode node = root;
        while(node!=null || !stack.isEmpty()){
            if(node!=null){
                stack.push(node);
                node = node.left;
            }
            else{
                node = stack.pop();//parent
                res.add(node.val);
                node = node.right;//iterate from the right
            }
        }
    }
}

你可能感兴趣的:(94. Binary Tree Inorder Traversal)