资讯专栏INFORMATION COLUMN

[Leetcode] Binary Tree Traversal 二叉树遍历

RaoMeng / 3290人阅读

摘要:栈迭代复杂度时间空间递归栈空间对于二叉树思路用迭代法做深度优先搜索的技巧就是使用一个显式声明的存储遍历到节点,替代递归中的进程栈,实际上空间复杂度还是一样的。对于先序遍历,我们出栈顶节点,记录它的值,然后将它的左右子节点入栈,以此类推。

Binary Tree Preorder Traversal

</>复制代码

  1. Given a binary tree, return the preorder traversal of its nodes" values.

  2. For example: Given binary tree {1,#,2,3},

  3. </>复制代码

    1. 1
    2. 2
    3. /
    4. 3
  4. return [1,2,3].

栈迭代 复杂度

时间 O(b^(h+1)-1) 空间 O(h) 递归栈空间 对于二叉树b=2

思路

用迭代法做深度优先搜索的技巧就是使用一个显式声明的Stack存储遍历到节点,替代递归中的进程栈,实际上空间复杂度还是一样的。对于先序遍历,我们pop出栈顶节点,记录它的值,然后将它的左右子节点push入栈,以此类推。

代码

</>复制代码

  1. public class Solution {
  2. public List preorderTraversal(TreeNode root) {
  3. Stack s = new Stack();
  4. List res = new LinkedList();
  5. if(root!=null) s.push(root);
  6. while(!s.isEmpty()){
  7. TreeNode curr = s.pop();
  8. res.add(curr.val);
  9. if(curr.right!=null) s.push(curr.right);
  10. if(curr.left!=null) s.push(curr.left);
  11. }
  12. return res;
  13. }
  14. }
Binary Tree Inorder Traversal

</>复制代码

  1. Given a binary tree, return the inorder traversal of its nodes" values.

  2. For example: Given binary tree {1,#,2,3},

  3. </>复制代码

    1. 1
    2. 2
    3. /
    4. 3
  4. return [1,3,2].

栈迭代 复杂度

时间 O(b^(h+1)-1) 空间 O(h) 递归栈空间 对于二叉树b=2

思路

用栈中序遍历没有先序遍历那么直观,因为我们不能马上pop出当前元素,而要先把它的左子树都遍历完才能pop它自己。所有我们先将将最左边的所有节点都push进栈,然后再依次pop并记录值,每pop一个元素后再看它有没有右子树,如果右的话,我们再将它的右节点和右子树中最左边的节点都push进栈,再依次pop。

代码

</>复制代码

  1. public class Solution {
  2. public List inorderTraversal(TreeNode root) {
  3. List res = new LinkedList();
  4. Stack s = new Stack();
  5. //先将最左边的节点都push进栈
  6. if(root!=null){
  7. pushAllTheLeft(s, root);
  8. }
  9. while(!s.isEmpty()){
  10. TreeNode curr = s.pop();
  11. res.add(curr.val);
  12. //如果有右子树,将右节点和右子树的最左边的节点都push进栈
  13. if(curr.right != null){
  14. pushAllTheLeft(s, curr.right);
  15. }
  16. }
  17. return res;
  18. }
  19. private void pushAllTheLeft(Stack s, TreeNode root){
  20. s.push(root);
  21. while(root.left!=null){
  22. root = root.left;
  23. s.push(root);
  24. }
  25. }
  26. }
Binary Tree Postorder Traversal

</>复制代码

  1. Given a binary tree, return the postorder traversal of its nodes" values.

  2. For example: Given binary tree {1,#,2,3},

  3. </>复制代码

    1. 1
    2. 2
    3. /
    4. 3
  4. return [3,2,1].

栈迭代 复杂度

时间 O(b^(h+1)-1) 空间 O(h) 递归栈空间 对于二叉树b=2

思路

后序遍历就不能简单的改变pop顺序来实现了,我们知道根节点(这里的根节点不是整个树的根,而是相对于左右节点的跟)是在左右节点都计算完才计算的,所以我们会遇到两次根节点,第一次遇到根节点时我们将左右节点加入栈,但不把根节点pop出去,等到处理完左右节点后,我们又会遇到一次根节点,这时再计算根节点并把它pop出去。为了判断是第一次还是第二次遇到这个根节点,我们可以用一个数据结构把这个信息封装进去,第一次遇到的时候将其设为已经访问了一次,这样第二次遇到时发现已经访问了一次,就可以直接pop了。

代码

</>复制代码

  1. public class Solution {
  2. public List postorderTraversal(TreeNode root) {
  3. Stack s = new Stack();
  4. List res = new LinkedList();
  5. if(root!=null) s.push(new PowerNode(root, false));
  6. while(!s.isEmpty()){
  7. PowerNode curr = s.peek();
  8. //如果是第二次访问,就计算并pop该节点
  9. if(curr.visited){
  10. res.add(curr.node.val);
  11. s.pop();
  12. } else {
  13. //如果是第一次访问,就将它的左右节点加入stack,并设置其已经访问了一次
  14. if(curr.node.right!=null) s.push(new PowerNode(curr.node.right, false));
  15. if(curr.node.left!=null) s.push(new PowerNode(curr.node.left, false));
  16. curr.visited = true;
  17. }
  18. }
  19. return res;
  20. }
  21. private class PowerNode {
  22. TreeNode node;
  23. boolean visited;
  24. public PowerNode(TreeNode n, boolean v){
  25. this.node = n;
  26. this.visited = v;
  27. }
  28. }
  29. }
反向法 复杂度

时间 O(b^(h+1)-1) 空间 O(h) 递归栈空间 对于二叉树b=2

思路

还有一种更巧妙的方法,因为后序遍历的顺序是left - right - root,虽然我们不方便直接得到这个顺序,但是它的逆序还是很好得到的,我们可以用root - right - left的顺序遍历树,然后反向添加结果就行了。

代码

</>复制代码

  1. public class Solution {
  2. public List postorderTraversal(TreeNode root) {
  3. Stack stk = new Stack();
  4. if(root != null) stk.push(root);
  5. LinkedList res = new LinkedList();
  6. while(!stk.isEmpty()){
  7. TreeNode curr = stk.pop();
  8. // 先添加左后添加右,就是先访问右后访问左
  9. if(curr.left != null) stk.push(curr.left);
  10. if(curr.right != null) stk.push(curr.right);
  11. // 反向添加结果,每次加到最前面
  12. res.offerFirst(curr.val);
  13. }
  14. return res;
  15. }
  16. }
Binary Tree Level Order Traversal I && II

</>复制代码

  1. Given a binary tree, return the bottom-up level order traversal of its nodes" values. (ie, from left to right, level by level from leaf to root).

  2. For example: Given binary tree {3,9,20,#,#,15,7},

  3. </>复制代码

    1. 3
    2. /
    3. 9 20
    4. /
    5. 15 7
  4. return its bottom-up level order traversal as: (II)

  5. </>复制代码

    1. [
    2. [15,7],
    3. [9,20],
    4. [3]
    5. ]
  6. return its level order traversal as: (I)

  7. </>复制代码

    1. [
    2. [3],
    3. [9,20],
    4. [15,7]
    5. ]
队列迭代 复杂度

时间 O(b^(h+1)-1) 空间 O(b^h)

思路

本题实质是广度优先搜索BFS,而用队列可以轻松的以迭代形式实现它。不过不同于BFS的是,层序遍历需要在队列中记住每一层的分割点,而BFS不关心层数只要遍历到指定元素就行了。为了记住这个分割点,我们在进入下一层之前先记下这一层的元素个数N(其实就是当前queue的大小),然后只遍历N个节点(展开下一层节点的同时queue中会新加入很多下下一层的节点)。遍历完N个节点后记录新的层数,再进入下一层。对于II,返回的层是逆序的,我们只要在结果中,每次把下面新一层加到当前这层的前面就行了

代码

</>复制代码

  1. public class Solution {
  2. public List> levelOrder(TreeNode root) {
  3. List> res = new LinkedList>();
  4. Queue q = new LinkedList();
  5. if(root != null) q.offer(root);
  6. while(!q.isEmpty()){
  7. int size = q.size();
  8. List level = new LinkedList();
  9. //控制当前层的遍历次数
  10. for(int i =0; i < size; i++){
  11. TreeNode curr = q.poll();
  12. level.add(curr.val);
  13. if(curr.left!=null) q.offer(curr.left);
  14. if(curr.right!=null) q.offer(curr.right);
  15. }
  16. res.add(level);
  17. //对于II, 我们要逆序加入
  18. //res.add(0, level)
  19. }
  20. return res;
  21. }
  22. }
Binary Tree Zigzag Level Order Traversal

</>复制代码

  1. Given a binary tree, return the zigzag level order traversal of its nodes" values. (ie, from left to right, then right to left for the next level and alternate between).

  2. For example: Given binary tree {3,9,20,#,#,15,7},

  3. </>复制代码

    1. 3
    2. /
    3. 9 20
    4. /
    5. 15 7
  4. return its zigzag level order traversal as:

  5. </>复制代码

    1. [
    2. [3],
    3. [20,9],
    4. [15,7]
    5. ]
队列迭代 复杂度

时间 O(b^(h+1)-1) 空间 O(b^h)

思路

ZigZag遍历时,奇数层正序记录,偶数层逆序记录。可以通过结果中已有的层数来判断。

代码

</>复制代码

  1. public class Solution {
  2. public List> zigzagLevelOrder(TreeNode root) {
  3. List> res = new LinkedList>();
  4. Queue q = new LinkedList();
  5. if(root != null) q.offer(root);
  6. while(!q.isEmpty()){
  7. int size = q.size();
  8. List level = new LinkedList();
  9. for(int i =0; i < size; i++){
  10. TreeNode curr = q.poll();
  11. //根据结果中已有的层数控制正序还是逆序
  12. if(res.size() % 2 == 0){
  13. level.add(curr.val);
  14. } else {
  15. level.add(0,curr.val);
  16. }
  17. if(curr.left!=null) q.offer(curr.left);
  18. if(curr.right!=null) q.offer(curr.right);
  19. }
  20. res.add(level);
  21. }
  22. return res;
  23. }
  24. }

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/64468.html

相关文章

  • LeetCode 之 JavaScript 解答第94题 —— 叉树的中序遍历

    摘要:小鹿题目二叉树中序遍历给定一个二叉树,返回它的中序遍历。通常递归的方法解决二叉树的遍历最方便不过,但是我还是喜欢增加点难度,用一般的迭代循环来实现。 Time:2019/4/25Title:Binary Tree Inorder TraversalDifficulty: MediumAuthor:小鹿 题目:Binary Tree Inorder Traversal(二叉树中序遍历...

    Jason 评论0 收藏0
  • leetcode-102-Binary Tree Level Order Traversal

    102. 二叉树的层次遍历 题目描述 给定一个二叉树,返回其按层次遍历的节点值。 (即zhucengde,从左到右访问)。 例如: 给定二叉树: [3,9,20,null,null,15,7], 3 / 9 20 / 15 7 返回其层次遍历结果为: [ [3], [9,20], [15,7] ] class Solution: def le...

    widuu 评论0 收藏0
  • leetcode讲解--94. Binary Tree Inorder Traversal

    摘要:题目地址嗯,经典的题目,中序遍历二叉树。代码如下中序遍历先序遍历后序遍历是不是简单的不要不要的,递归就是这么美。右孩子后压栈全部释放出来嗯,总的来说用迭代遍历确实烧脑,没什么性能上的特殊需求还是用递归写法吧,对程序员友好哦。 94. Binary Tree Inorder Traversal Given a binary tree, return the inorder travers...

    henry14 评论0 收藏0
  • leetcode-145-Binary Tree Postorder Traversal

    摘要:栈的意义价值具有时间性,先进后出。比如递归的后序遍历,先序遍历,二叉树的按层次打印。根据需求不同,在中暂时储存的元素单元也不同,元素的先后顺序也不同。应用对顺序有要求的数据。 stack 栈的意义价值: 具有时间性,先进后出。 所以具有时间关联顺序的元素可以通过这个时间。 比如递归的后序遍历,先序遍历, 二叉树的按层次打印。 根据需求不同,在stack中暂时储存的元素...

    Pandaaa 评论0 收藏0

发表评论

0条评论

RaoMeng

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<