Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree
Given binary tree
{1,#,2,3}, 1
\
2
/
3
return
[1,2,3].
Note: Recursive solution is trivial, could you do it iteratively?
Solution:
A stack is necessary when there is no parent pointer available in the tree.
Pre-order: root-left-right. We are going to traverse left child first, accordingly, we will push right child first.
Solution:
A stack is necessary when there is no parent pointer available in the tree.
Pre-order: root-left-right. We are going to traverse left child first, accordingly, we will push right child first.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList preorderTraversal(TreeNode root) {
ArrayList ret = new ArrayList();
Stack stack = new Stack();
if(root == null) return ret;
stack.push(root);
while(!stack.isEmpty()){
TreeNode node = stack.pop();
ret.add(node.val);
if(node.right != null) stack.push(node.right);
if(node.left != null) stack.push(node.left);
}
return ret;
}
}
No comments:
Post a Comment