LeetCode 094 Binary Tree Inorder Traversal

题目


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

中序遍历,递归、迭代两种方式


思路


1 练习,练习,练习

2 递归很简单

3 迭代中序比前序要难一点,但是思路清楚的话,还是很容易写的。


代码


1  递归

public class Solution {
    public ArrayList inorderTraversal(TreeNode root) {
        ArrayList ans = new ArrayList();
        useme(root,ans);
        return ans;
    }
    public void useme(TreeNode root,ArrayList ans){
        if(root!=null){
            useme(root.left,ans);
            ans.add(root.val);
            useme(root.right,ans);
        }
    }
}

2 迭代

public class Solution {
    public ArrayList inorderTraversal(TreeNode root) {
        ArrayList ans = new ArrayList();
        LinkedList stack = new LinkedList();
        if(root==null){
            return ans;
        }
        TreeNode cur = root;
        while(true){
            while(cur!=null){
                stack.push(cur);
                cur = cur.left;
            }
            if(stack.isEmpty()){
                break;
            }
            cur = stack.pop();
            ans.add(cur.val);
            cur = cur.right;
        }
        return ans;
    }
}

15.4.8
public class Solution {
    public List inorderTraversal(TreeNode root) {
        List ans = new ArrayList();
        LinkedList stack = new LinkedList();
        
        if(root == null){
            return ans;
        }
        TreeNode cur = root;
        while((!stack.isEmpty()) || cur !=null){
            while(cur!=null){
                stack.push(cur);
                cur = cur.left;
            }
            
            cur = stack.pop();
            ans.add(cur.val);
            cur = cur.right;
        }
        return ans;
    }
}

更新的写法更加好记,只要 栈不为空 或者 目前节点还有,就继续玩下去。这样的判断非常直观。

你可能感兴趣的:(LeetCode)