Binary Tree Inorder Traversal

Given a binary tree, return the inorder traversal of its nodes’ values (solved by using stack)

public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> returnList = new ArrayList<Integer> ();  
        if (root == null) {
            return returnList;
        }
        
        Stack<TreeNode> stack = new Stack<TreeNode> (); 
        TreeNode p = root; 
        
        while (!stack.empty() || p != null) {
            if (p != null) {
                stack.push (p);
                p = p.left;
            } else {
                TreeNode t = stack.pop (); 
                returnList.add(t.val);
                p = t.right; 
            }
        }
        return returnList; 
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s