Binary Tree Inorder Tranversal

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].

Solution:

/**
 * 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<Integer> inorderTraversal(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        Stack<TreeNode> st = new Stack<>();
        while(root!=null){
            st.push(root);
            root = root.left;
        }
        while(!st.isEmpty()){
            ans.add(st.peek().val);
            TreeNode cur = st.pop().right;
            while(cur!=null){
                st.push(cur);
                cur = cur.left;
            }
        }
        return ans;
    }
}

Solution:

public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        while(root!=null || !stack.isEmpty()){
            while(root!=null){
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            ans.add(root.val);
            root = root.right;
        }
        return ans;
    }
}
comments powered by Disqus