Description
https://leetcode.com/problems/binary-tree-preorder-traversal/
Solving Ideas
前序遍历
Solution
递归
import java.util.*;
class Solution {
private void preorderCore(TreeNode root, List<Integer> res){
if(root == null) return;
res.add(root.val);
preorderCore(root.left, res);
preorderCore(root.right, res);
}
public List<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> res = new ArrayList<>();
preorderCore(root, res);
return res;
}
}
非递归
import java.util.*;
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> res = new ArrayList<>();
if(root == null) return res;
LinkedList<TreeNode> stack = new LinkedList<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode node = stack.pop();
res.add(node.val);
if(node.right != null) stack.push(node.right);
if(node.left != null) stack.push(node.left);
}
return res;
}
}