Java accepted solution


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

Log in to reply
 

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