• 剑指offer55. 平衡二叉树


    输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。

    方法1:后序遍历二叉树,先判断子树是不是平衡树,如果不是,直接返回,此处利用了剪枝的思想

    time: $O(n)$

    space: $O(n)$

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int dfs(TreeNode* u) {
            if (!u) return 0;
            int left = dfs(u->left);
            if (left == -1) return -1;
            int right = dfs(u->right);
            if (right == -1) return -1;
            return abs(left - right) < 2 ? max(left,right) + 1 : -1;
        }
        
        bool isBalanced(TreeNode* root) {
            return dfs(root) != -1;
        }
    };

    方法2:先序遍历二叉树,先判断当前树是不是平衡树,需要一个计算左右子树深度的函数,然后再判断左右子树是否为平衡二叉树,此处有大量重复计算

    time: $O(nlog(n))$

    space: $O(n)$

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int dep(TreeNode* u) {
            if (!u) return 0;
            return 1 + max(dep(u->left), dep(u->right));
        }
        bool isBalanced(TreeNode* root) {
            if (!root) return true;
            int ld = dep(root->left);
            int rd = dep(root->right);
            if (abs(ld - rd) > 1) return false;
            return isBalanced(root->left) && isBalanced(root->right);
        }
    };
  • 相关阅读:
    LeetCode-160. Intersection of Two Linked Lists
    LeetCode-328. Odd Even Linked List
    LeetCode-234. Palindrome Linked List
    Trie树
    圆圈中最后剩下的数字
    LeetCode-215. Kth Largest Element in an Array
    n个骰子的和
    DFS & BFS
    ubuntu14.04安装显卡驱动(转载)
    Ubuntu 14.04 配置caffe环境
  • 原文地址:https://www.cnblogs.com/betaa/p/12660725.html
Copyright © 2020-2023  润新知