preorder traversal in JAVA using a stack


  • 0
    S

    /**

    • 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) {
      Stack<TreeNode> stack = new Stack<>();
      ArrayList<Integer> result = new ArrayList<>();
      TreeNode node = root;
      while(node != null){
      result.add(node.val);
      stack.push(node);
      node = node.left;
      }
      while(!stack.isEmpty()){
      TreeNode tree = stack.pop();
      if(tree.right != null){
      tree = tree.right;
      result.add(tree.val);
      stack.push(tree);
      while(tree.left != null){
      tree = tree.left;
      result.add(tree.val);
      stack.push(tree);
      }
      }
      }
      return result;
      }
      }

Log in to reply
 

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