Easy to understand Iterative java solution


  • 0
    R
    public class Solution {
        public List<Integer> inorderTraversal(TreeNode root) {
            final List<Integer> inorderResult = new ArrayList<Integer>();
            if(root == null) {
                return inorderResult;
            }
            
            TreeNode cur = root;
            final Stack<TreeNode> stack = new Stack<TreeNode>();
            while(cur != null || !stack.isEmpty()) {
                if(cur != null) {
                    stack.push(cur);
                    cur = cur.left;
                } else {
                    cur = stack.pop();
                    inorderResult.add(cur.val);
                    cur = cur.right;
                }
            }// end while
            
            return inorderResult;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.