1ms using stack


  • 0
    D
    public class Solution {
        public List<Integer> inorderTraversal(TreeNode root) {
            ArrayDeque<TreeNode> deque = new ArrayDeque<TreeNode>();    
            List<Integer> list = new ArrayList<Integer>();
            
            if(root != null)
            {
                deque.addFirst(root);
            }
            
            while(deque.size() > 0)
            {
                TreeNode node = deque.removeFirst();
                if(node.left != null)
                {
                    TreeNode leftNode = node.left;
                    node.left = null;
                    deque.addFirst(node);
                    deque.addFirst(leftNode);
                }
                else
                {
                    list.add(node.val);
                    if(node.right != null)
                    {
                        deque.addFirst(node.right);
                    }
                }
            }
            
            return list;
        }
    }
    

  • 1
    H

    wouldn't
    node.left = null
    modify the original tree?


Log in to reply
 

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