递归
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
traversal(root, list);
return list;
}
public void traversal(TreeNode t, List<Integer> list) {
if (t == null) {
return;
}
list.add(t.val);
traversal(t.left, list);
traversal(t.right, list);
}
迭代(不断走向左子树)
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
Deque<TreeNode> stack = new LinkedList<>();
TreeNode t = root;
while (!stack.isEmpty() || t != null) {
if (t != null) {
list.add(t.val);
stack.push(t);
t = t.left;
} else {
// t已经被遍历过,再拿出来的时候需要遍历t的右子树
t = stack.pop();
t = t.right;
}
}
return list;
}
迭代(先放右子树,再放左子树)
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
Deque<TreeNode> stack = new LinkedList<>();
if(root==null)return list;
TreeNode t = root;
stack.push(t);
while (!stack.isEmpty()) {
t = stack.pop();
list.add(t.val);
if (t.right != null) {
stack.push(t.right);
}
if (t.left != null) {
stack.push(t.left);
}
}
return list;
}
文章来源地址https://www.toymoban.com/news/detail-815324.html
文章来源:https://www.toymoban.com/news/detail-815324.html
到了这里,关于144.二叉树的前序遍历的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!