原题描述:
Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree{1,#,2,3},
分析:
先序遍历,遍历顺序为:根节点 -> 左子树 -> 右子树
代码:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.ArrayList;
public class Solution {
ArrayList<Integer> resList = new ArrayList<Integer>();
public ArrayList<Integer> preorderTraversal(TreeNode root) {
if(root == null) return resList; // 停止条件
resList.add(root.val); // 根
preorderTraversal(root.left); // 左
preorderTraversal(root.right); // 右
return resList;
}
}