zoukankan      html  css  js  c++  java
  • 【剑指Offer-知识迁移能力】面试题55.2:平衡二叉树

    题目描述

    输入一棵二叉树,判断该二叉树是否是平衡二叉树。

    思路1

    求出左右子树的长度来判断。代码如下:

    class Solution {
    public:
        bool IsBalanced_Solution(TreeNode* pRoot) {
            if(pRoot==nullptr)
                return true;
            
            int leftDepth = getDepth(pRoot->left);
            int rightDepth = getDepth(pRoot->right);
            int delta = leftDepth-rightDepth;
            if(delta<-1 || delta>1)
                return false;
            return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right);
        }
        
        int getDepth(TreeNode* pRoot){
            if(pRoot==nullptr)
                return 0;
            
            int left = getDepth(pRoot->left)+1;
            int right = getDepth(pRoot->right)+1;
            if(left>right)
                return left;
            else return right;
        }
    };
    

    思路2

    思路1先根据根结点的左右子树深度判断是否是平衡二叉树,然后根据左右子树的左右子树判断,是从上到下的过程,这一过程底层的节点会被重复遍历,影响性能。如果我们用后序遍历的方式遍历每个节点,那么在遍历一个节点之前,我们就已经遍历了它的左右子树,如果记录左右子树的深度,我们就可以一边遍历一边判断每个节点是否是平衡的。这样的话,每个节点只会被遍历一次。代码如下:

    class Solution {
    public:
        bool IsBalanced_Solution(TreeNode* pRoot) {
            if(pRoot==nullptr)
                return true;
            
            int depth = 0;
            return isBalanced(pRoot, depth);
        }
        
        bool isBalanced(TreeNode* pRoot, int& depth){
            if(pRoot==nullptr){
                depth = 0;
                return true;
            }
            
            int left, right;
            if(isBalanced(pRoot->left, left) && isBalanced(pRoot->right, right)){
                int delta = left - right;
                if(delta<=1 && delta>=-1){
                    depth = 1+(left>right?left:right);
                    return true;
                }
            }
            return false;
        }
    };
    
  • 相关阅读:
    HDU 2433 Travel (最短路,BFS,变形)
    HDU 2544 最短路 (最短路,spfa)
    HDU 2063 过山车 (最大匹配,匈牙利算法)
    HDU 1150 Machine Schedule (最小覆盖,匈牙利算法)
    290 Word Pattern 单词模式
    289 Game of Life 生命的游戏
    287 Find the Duplicate Number 寻找重复数
    283 Move Zeroes 移动零
    282 Expression Add Operators 给表达式添加运算符
    279 Perfect Squares 完美平方数
  • 原文地址:https://www.cnblogs.com/flix/p/12520143.html
Copyright © 2011-2022 走看看