问题:
Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree [1,null,2,3]
,
1 \ 2 / 3
return [1,2,3]
.
Note: Recursive solution is trivial, could you do it iteratively?
解决:
① 求出先根遍历的结果,递归方法。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {//1ms
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
return preorder(root,res);
}
public List<Integer> preorder(TreeNode root,List<Integer> res){
if(root == null) return res;
res.add(root.val);
preorder(root.left,res);
preorder(root.right,res);
return res;
}
}
② 非递归方法,使用栈实现。
class Solution { //1ms
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
if(root != null){
stack.push(root);
while(! stack.isEmpty()){
TreeNode cur = stack.pop();
res.add(cur.val);
if(cur.right != null){
stack.push(cur.right);
}
if(cur.left != null){
stack.push(cur.left);
}
}
}
return res;
}
}