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