中序遍历二叉树

左  根  右

 

1. 递归

class Solution {
    private List<Integer> res = new ArrayList<>();
    public List<Integer> inorderTraversal(TreeNode root) {
        recur(root);
        return res;
    }
    
    void recur(TreeNode root){
        if(root==null)
            return;
        recur(root.left);
        res.add(root.val);
        recur(root.right);
    }
}

 

2. 迭代

  将左子结点遍历到底,依次加入到队列中,然后弹出

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<TreeNode> stack = new ArrayList<>();
        List<Integer> res = new ArrayList<>();
        while(queue.size()>0 ||root!=null){
            while(root!=null){
                stack.add(root);
                root=root.left;
            }
            root = stack.remove(queue.size()-1);
            res.add(root.val);
            root=root.right;
        }                
        return res;
    }
}

 

posted @ 2020-08-19 15:49  你眼里的星辰  阅读(90)  评论(0)    收藏  举报