My AC Java Solution with Iteration


  • 1
    S
    public class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        
        Stack<TreeNode> st = new Stack<TreeNode>();
        List<Integer> result = new ArrayList<Integer>();
        st.push(root);
        while(!st.isEmpty())
        {
            TreeNode n = st.pop();
            if(n!=null)
            {
                result.add(n.val);
                st.push(n.right);
                st.push(n.left);
                
            }
        }
        return result;
        
    }
    

    }


Log in to reply
 

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