Java solution with Stack iteration, push in the order: root->right->left


  • 0
    public class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res=new ArrayList<Integer>();
        Stack<TreeNode> s=new Stack<TreeNode>();
        if(root==null)
            return res;
        s.push(root);
        TreeNode node;
        while(!s.empty()){
            node=s.pop();
            res.add(node.val);
            if(node.right!=null)
                s.push(node.right);
            if(node.left!=null)
                s.push(node.left);
        }
        return res;
    }
    

    }


Log in to reply
 

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