描述:
给出一棵二叉树,返回其节点值的前序遍历。
样例
给出一棵二叉树 {1,#,2,3}
,
1 \ 2 / 3
返回 [1,2,3]
.
Java代码:
/**
* 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) {
ArrayList<Integer> list= new ArrayList<Integer>();
traversal(list,root);
return list;
}
public void traversal(ArrayList<Integer> list,TreeNode root){
if(root == null){
return;
}
list.add(root.val);
traversal(list,root.left);
traversal(list,root.right);
}
}