Iterative Solution Java


  • 0
    U
        public List<Integer> preorderTraversal(TreeNode root) {
            List<Integer> result = new LinkedList<>();
            if(root==null) return result;
            Stack<TreeNode> st = new Stack<>();
            st.push(root);
            
            while(!st.isEmpty()){
                TreeNode now = st.pop();
                result.add(now.val);
                
                if(now.right!=null) st.push(now.right);
                if(now.left!=null) st.push(now.left);
            }
            
            return result;
        }
    }

Log in to reply
 

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