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;
        }
    };
    
  • 相关阅读:
    Spring多数据源动态切换
    IntelliJ Idea使用代码格式化,Tab制表符进行缩进
    idea 快捷键
    final关键字的功能概述
    IntelliJ Idea 常用快捷键列表
    Log4j.properties配置详解
    IDEA添加try catch快捷键
    使用 JMeter 进行压力测试
    idea 复制当前行到下一行快捷键
    js父窗口opener与parent
  • 原文地址:https://www.cnblogs.com/flix/p/12520143.html
Copyright © 2011-2022 走看看