原题
给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3] 1
\
2
/
3
输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
解法
思想
递归、迭代,类似 leetcode94-二叉树的中序遍历
代码
递归:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<Integer> ans = new ArrayList<>();
public List<Integer> preorderTraversal(TreeNode root) {
if(root!=null){
ans.add(root.val);
preorderTraversal(root.left);
preorderTraversal(root.right);
}
return ans;
}
}
迭代:
public class Solution {
public List <Integer> inorderTraversal(TreeNode root) {
List <Integer> res = new ArrayList<>();
Stack <TreeNode> stack = new Stack<>();
TreeNode curr = root;
while (curr != null || !stack.isEmpty()) {
while (curr != null) {
stack.push(curr);
res.add(curr.val);
curr = curr.left;
}
curr = stack.pop();
curr = curr.right;
}
return res;
}
}
原创文章,作者:彭晨涛,如若转载,请注明出处:https://www.codetool.top/article/leetcode144-%e4%ba%8c%e5%8f%89%e6%a0%91%e7%9a%84%e5%89%8d%e5%ba%8f%e9%81%8d%e5%8e%86/