Leetcode – Binary Tree Preorder Traversal (Java)
Preorder binary tree traversal is a classic interview problem. The key to solve this problem is using a stack to store left and right children, and push right child first so that it is processed after the left child.
Java Solution
public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public class Solution { public ArrayList<Integer> preorderTraversal(TreeNode root) { ArrayList<Integer> returnList = new ArrayList<Integer>(); if(root == null) return returnList; Stack<TreeNode> stack = new Stack<TreeNode>(); stack.push(root); while(!stack.empty()){ TreeNode n = stack.pop(); returnList.add(n.val); if(n.right != null){ stack.push(n.right); } if(n.left != null){ stack.push(n.left); } } return returnList; } } |
<pre><code> String foo = "bar"; </code></pre>
-
shuchi sinha
-
kedi kebba
-
Robina Li
-
Bendells
-
fishwen
-
Prabhat Kumar Kashyap
-
abgalphabet