给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [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> list=new ArrayList<>();
if(root==null) return list;
recursion(root,list);
return list;
}
public void recursion(TreeNode root,List<Integer> list){
if(root==null) return;
else{
list.add(root.val);
recursion(root.left,list);
recursion(root.right,list);
}
}
}
二、迭代
/**
* 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> list=new ArrayList<>();
Stack<TreeNode> stack=new Stack<>();
if(root==null) return list;
stack.push(root);
while(!stack.isEmpty()){
TreeNode curr=stack.pop();
list.add(curr.val);
if(curr.right!=null) stack.push(curr.right);
if(curr.left!=null) stack.push(curr.left);
}
return list;
}
}