Simple stack iterative JAVA


  • 0
    I
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public List<Integer> preorderTraversal(TreeNode root) {
            List<Integer> res = new ArrayList<Integer>();
            if(null == root) return res;
            
            Stack<TreeNode> q = new Stack<TreeNode>();
            q.push(root);
            
            while(!q.isEmpty()) {
                TreeNode node = q.pop();
                res.add(node.val);
                
                if(null != node.right) {
                    q.push(node.right);
                }
                if(null != node.left) {
                    q.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.