For example:
Given binary tree
{1,#,2,3}
,1 \ 2 / 3return
[1,2,3]
.
Note: Recursive solution is trivial, could you do it iteratively?
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> pre = new LinkedList<>(); Stack<TreeNode> stack = new Stack<>(); TreeNode node = root; while (!stack.isEmpty() || node != null) { if (node != null) { // Center pre.add(node.val); if (node.right != null) stack.push(node.right); // Left node = node.left; } else // Right node = stack.pop(); } return pre; } }
No comments:
Post a Comment