/*
stack 的解法
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<TreeNode>();
List<Integer> rst = new ArrayList<Integer>();
if (root == null) {
return rst;
}
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
rst.add(node.val);
if (node.right != null) {
stack.push(node.right);
}
if (node.left != null) {
stack.push(node.left);
}
}
return rst;
}
}
/*
divide and conquer
*/
/**
* Definition for a binary tree node.
* 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> rst = new ArrayList<Integer>();
if (root == null) {
return rst;
}
List<Integer> left = preorderTraversal(root.left);
List<Integer> right = preorderTraversal(root.right);
rst.add(root.val);
rst.addAll(left);
rst.addAll(right);
return rst;
}
}