題目:
給定一個二叉樹,返回它的 前序 遍歷。
示例:
輸入: [1,null,2,3]
1
\
2
/
3
輸出: [1,2,3]
進階: 遞歸算法很簡單,你可以通過迭代算法完成嗎?
遞歸法:
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
helper(root, res);
return res;
}
public void helper(TreeNode root, List<Integer> res) {
if (root != null) {
res.add(root.val);
if (root.left != null) {
helper(root.left, res);
}
if (root.right != null) {
helper(root.right, res);
}
}
}
}
迭代法:
利用棧
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
if(root==null) return res;
stack.push(root);
//先進後出
while (!stack.isEmpty()) {
TreeNode curr = stack.pop();
res.add(curr.val);
if(curr.right!=null){
stack.push(curr.right);
}
if(curr.left!=null){
stack.push(curr.left);
}
}
return res;
}
}