难度简单610收藏分享切换为英文接收动态反馈
给你二叉树的根节点 root ,返回它节点值的 前序 遍历。
示例 1:
输入:root = [1,null,2,3]
输出:[1,2,3]
示例 2:
输入:root = []
输出:[]
示例 3:
输入:root = [1]
输出:[1]
示例 4:
输入:root = [1,2]
输出:[1,2]
示例 5:
输入:root = [1,null,2]
输出:[1,2]
递归
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
return forward(res,root);
}
public static List<Integer> forward( List<Integer> res,TreeNode root){
if(root==null) return res;
res.add(root.val);
forward(res,root.left);
forward(res,root.right);
return res;
}
}
迭代
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
Stack<TreeNode> stk = new Stack<TreeNode>();
TreeNode p = root;
while(p!=null||!stk.isEmpty()){
while(p!=null){
res.add(p.val);
stk.add(p);
p = p.left;
}
p = stk.pop();
p = p.right;
}
return res;
}
}
|