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

Method 1. divide and conquer
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();

        if(root == null) return res;

        List<Integer> left = inorderTraversal(root.left);
        List<Integer> right = inorderTraversal(root.right);

        res.addAll(left);
        res.add(root.val);
        res.addAll(right);

        return res;
    }
}

Method 2. use iteration with stack
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();

        if(root == null) return res;

       while(root != null || !stack.empty()) {  //只有在root为null并且stack为空的时候循环结束
           if(root != null) {
               stack.push(root);
               root = root.left;
           }else{
               root = stack.pop();
               res.add(root.val);
               root = root.right;
           }
       }
        return res;
    }
}

results matching ""

    No results matching ""