zoukankan      html  css  js  c++  java
  • leetcode-0226 翻转二叉树

    题目地址 https://leetcode-cn.com/problems/invert-binary-tree/

    1.递归

    时间复杂度O(n) 空间复杂度O(n)
    递归的思路首先要找到递归的终止条件,这题递归的终止条件必须要是当前的节点为null才可以结束递归。或者我们可以换个角度来思考,如果这个节点不为null,那它就可能还存在子节点,这种情况我们是可以继续向下递归的。
    第二个使我们必须了解递归的过程,本题的递归主要是为了翻转node节点的左右子树,invertTree函数是为了找到以root为根的节点,将整棵树翻转,并将翻转之后的结果返回。有了这个理解之后,我们就可以用同样的方式理解代码中的 invertTree(root.left)invertTree(root.right)

    var invertTree = function(root) {
      if (root === null) {
        return null
      }
      const left = invertTree(root.left)
      const right = invertTree(root.right)
      root.left = right
      root.right = left
      return root
    };
    

    2.广度优先遍历(BFS)

    时间复杂度O(n) 空间复杂度O(n)
    这题由于需要将二叉树中的每个节点的左右子树交换,那我们需要访问二叉树的每个节点才行,显然这种每个节点都需要访问,但是无关顺序的问题,BFS和DFS两种方案都可以。

    class Solution {
        // BFS
        public TreeNode invertTree(TreeNode root) {
            Queue<TreeNode> queue = new LinkedList<>();
            if (root == null)
                return null;
            queue.offer(root);
            while (!queue.isEmpty()) {
                TreeNode node = queue.poll();
                TreeNode tmp = node.left;
                node.left = node.right;
                node.right = tmp;
    
                if (node.left != null)
                    queue.offer(node.left);
                if (node.right != null)
                    queue.offer(node.right);
            }
            return root;
        }
    }
    

    3.深度优先遍历(DFS)

    var invertTree = function(root) {
      if (root === null) {
        return root
      }
      const stack = []
      stack.push(root)
      while (stack.length) {
        const node = stack.pop()
        let tmp = node.left
        node.left = node.right
        node.right = tmp
        node.left && stack.push(node.left)
        node.right && stack.push(node.right)
      }
      return root
    };
    

    更多Leetcode题解和数据结构方面的问题可以关注我的githubhttps://github.com/GuoLizhi/algorithm/

  • 相关阅读:
    背下来就是电脑高手(转)
    split+ Pattern切割字符串
    java中方法中声明三个点“...”作用
    MRUnit测试
    configuration默认设置
    chmod|chown|chgrp和用法和区别
    hadoop 一些文件操作
    关闭SVN服务
    Hadoop如何计算map数和reduce数
    链式mapreduce
  • 原文地址:https://www.cnblogs.com/guolizhi/p/12767835.html
Copyright © 2011-2022 走看看