LeetCode 144. Binary Tree Preorder Traversal solution report
144. Binary Tree Preorder TraversalMy SubmissionsQuestionTotal Accepted: 108336 Total Submissions: 278322 Difficulty: Medium
Given a binary tree, return thepreordertraversal of its nodes 'values.
For example:
Given binary tree{1,#,2,3},
1 \ 2 / 3
Return[1,2,3].
Note: Recursive solution is trivial, cocould you do it iteratively?
Subscribeto see which companies asked this question
Show TagsShow Similar ProblemsHave you met this question in a real interview? YesNo
Returns the first root traversal order of a binary tree. The recursive solution is very simple. Can it be solved in a non-recursive way.
When traversing a node, the right child is added to the stack. Search left until it is empty.
My AC code
public class BinaryTreePreorderTraversal {public List
preorderTraversal(TreeNode root) { List
list = new ArrayList
(); Stack
stack = new Stack
(); TreeNode cur = root; while (cur != null || !stack.isEmpty()) {while (cur != null) {list.add(cur.val);if(cur.right != null) stack.add(cur.right);cur = cur.left;}if(!stack.isEmpty()) cur = stack.pop();} return list; }}