94 Binary Tree Inorder Traversal

递归的代码是以前数据结构书上常见的:

    public ArrayList<Integer> inorderTraversal(ConstructBinaryTreefromPostorderandInorderTraversal.TreeNode root) {
        ArrayList<Integer> res = new ArrayList<>();
        dfs(res, root);
        return res;
    }

    private void dfs(List<Integer> res, ConstructBinaryTreefromPostorderandInorderTraversal.TreeNode node) {
        if (node == null) return;
        dfs(res, node.left);
        res.add(node.val);
        dfs(res, node.right);
    }
复制代码

非递归用stack模拟中序遍历,要理解啊,不能死记硬背。注意while条件和while里面的if。

public class Solution {
        public ArrayList<Integer> inorderTraversal(TreeNode root) {
            ArrayList<Integer> res = new ArrayList<>();
            LinkedList<TreeNode> stack = new LinkedList<>();
            //注意while条件是或
            while (root != null || !stack.isEmpty()){
                if (root!=null){
                    stack.push(root);
                    root = root.left;
                }else {
                    root = stack.pop();
                    res.add(root.val);
                    root = root.right;
                }
            }
            return res;
        }
}
复制代码

MAR 25TH 这题今天做98. Validate Binary Search Tree 的时候又来复习了一遍,又忘的差不多了。。记得当时还在考虑为什么while里面要用||而不是&&。

这题还可以这样写:

public List<Integer> inorderTraversal(TreeNode root) {
    List<Integer> list = new ArrayList<>();
    if(root == null) return list;
    Stack<TreeNode> stack = new Stack<>();
    while(root != null || !stack.empty()){
        while(root != null){
            stack.push(root);
            root = root.left;
        }
        root = stack.pop();
        list.add(root.val);
        root = root.right;
        
    }
    return list;
}
复制代码

JULY 29 REVIEW

又看了一遍迭代的方法,仍然写不出。。上面那个代码,两个while循环其实挺清晰的,但是root = root.right那边还是挺难想到的。还有就是外层的while,两种情况;1是root!= null的情况,这种比较好考虑,就是首次进入的时候;2是root==null的情况,statck不为空,这种就是dfs到栈最底的情况。

转载于:https://juejin.im/post/5a3131526fb9a044fa19dcc9

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值