LintCode Binary Tree Preorder Traversal

时间:2022-06-27 23:28:32

Given a binary tree, return the preorder traversal of its nodes' values.

Given:

    1
/ \
2 3
/ \
4 5

return [1,2,4,5,3].

Thinking:

For this problem, you need to think about using recursive or non-recursive methods. As recursive method, we should think the order of traverse is to visit the node itself then visit left and right subtrees for traverse. So use a helper method to pass the list into which to acomplish hte adding of numbers to hte list.

/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: Preorder in ArrayList which contains node values.
*/
public ArrayList<Integer> preorderTraversal(TreeNode root) {
// write your code here
ArrayList<Integer> result = new ArrayList<Integer>();
if (root == null) {
return result;
}
traverse(root,result);
return result;
}
public void traverse (TreeNode root,ArrayList<Integer> list) {
if (root == null) {
return;
}
list.add(root.val);
traverse(root.left,list);
traverse(root.right,list);
}
}

For non-recursive method, think about using a stack to push nodes in order of right first then left. Because this order will lead to right node is always below the left node. Meanwhile, before finishing the left node's children and decedents you will go deep until leaves.

/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: Preorder in ArrayList which contains node values.
*/
public ArrayList<Integer> preorderTraversal(TreeNode root) {
// write your code here
// use stack to achieve pre-order
Stack<TreeNode> stack = new Stack<TreeNode>();
ArrayList<Integer> result = new ArrayList<Integer>();
stack.push(root);
// eadge case
if (root == null) {
return result;
}
// while loop to traverse every node in tree
while (!stack.isEmpty()) {
TreeNode curr = stack.pop();
result.add(curr.val);
if (curr.right != null) {
stack.push(curr.right);
}
if (curr.left != null) {
stack.push(curr.left);
}
} return result;
} }