Short and Easy iterative Java solution. Stack.

  • 0
        public List<Integer> preorderTraversal(TreeNode root) {
            List<Integer> list = new ArrayList<Integer>();
            if(root == null) return list;
            Stack<TreeNode> stack = new Stack<TreeNode>();
            TreeNode tmp = null;
            while(!stack.isEmpty()) {
                tmp = stack.pop();
                if (tmp.right != null) stack.push(tmp.right);
                if (tmp.left != null) stack.push(tmp.left);
            return list;

Log in to reply

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