给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
递归:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer>pre = new LinkedList<>();
preorder(root,pre);
return pre;
}
public void preorder(TreeNode root,List<Integer>ans){
if(root == null){
return;
}
ans.add(root.val);
preorder(root.left,ans);
preorder(root.right,ans);
}
}
迭代:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
List<Integer>out = new LinkedList<>();
if(root == null)
return out;
stack.push(root);
while (!stack.empty()){
TreeNode node = stack.pop();
out.add(node.val);
if(node.right != null){
stack.push(node.right);
}
if(node.left != null){
stack.push(node.left);
}
}
return out;
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
LinkedList<TreeNode> stack = new LinkedList<>();
List<Integer>out = new LinkedList<>();
if(root == null)
return out;
stack.push(root);
while (!stack.isEmpty()){
TreeNode node = stack.pop();
out.add(node.val);
if(node.right != null){
stack.push(node.right);
}
if(node.left != null){
stack.push(node.left);
}
}
return out;
}
}
推荐使用LinkedList来模拟Stack,时间会更快,因为Stack的底层是vector