Java Solution Iterative


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

Log in to reply
 

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