题目Binary Tree Preorder Traversal
Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1
2
/
3
return [1,2,3].
Note: Recursive solution is trivial, could you do it iteratively?
1,递归
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
dfs(root, result);
return result;
}
private void dfs(TreeNode root, List<Integer> result){
if(root == null){
return;
}
result.add(root.val);
dfs(root.left,result);
dfs(root.right,result);
}
2,非递归
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
if(root != null){
stack.push(root);
}
TreeNode tempNode = null;
while(!stack.empty()){
tempNode = stack.pop();
result.add(tempNode.val);
if(tempNode.right != null){
stack.push(tempNode.right);
}
if(tempNode.left != null){
stack.push(tempNode.left);
}
}
return result;
}