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]
.
用递归算法还是比较简单的:
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { List<Integer> re = new ArrayList<Integer>(); //先序遍历二叉树 public void PSF(TreeNode N) { if(N!=null) { re.add(N.val); if(N.left!=null) PSF(N.left); if(N.right!=null) PSF(N.right); } } public List<Integer> preorderTraversal(TreeNode root) { PSF(root); return re; } }