AC in Java, but 380 ms. Can anyone help me to optimize my code? Thx!


  • 0
    M

    public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
    ArrayList<Integer> result = new ArrayList<Integer>();

        if(root != null){
            ArrayDeque<TreeNode> stack = new ArrayDeque<TreeNode>();
            TreeNode node = root;
            stack.addFirst(node);
            while(!stack.isEmpty())
            {   
                if( node.left != null )
                {
                    stack.addFirst(node);
                    TreeNode temp = node;
                    node = node.left;
                    temp.left = null;
                }
                else
                {
                    result.add(node.val);
                    if( node.right != null )
                    {
                    //  stack.addFirst(node.right);
                     node = node.right;
                    }
                    else
                     node = stack.removeFirst();
                }
                
            }
        }
        return result;
    }
    

    }


Log in to reply
 

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