zoukankan      html  css  js  c++  java
  • 平衡二叉树

    平衡二叉树

    题目描述

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

    不是很懂, 一边递归一边判断, 可以消除节点遍历两次

    class Solution {
    public:
        bool IsBalanced_Solution(TreeNode *pRoot, int *pDepth) {
            if (nullptr == pRoot) {
                *pDepth = 0;
                return true;
            }
            int left = 0;
            int right = 0;
            if ((IsBalanced_Solution(pRoot->left, &left)) 
                && IsBalanced_Solution(pRoot->right, &right)) {
                int dif = left - right;
                if ((dif >= -1) && (dif <= 1)) {
                    *pDepth = 1 + (left > right ? left : right);
                    return true;
                }
            }
            
            return false;
        }
        
        bool IsBalanced_Solution(TreeNode* pRoot) {
            int depth = 0;
            
            return IsBalanced_Solution(pRoot, &depth);
        }
    };
    

    递归判断布尔变量方法学学, 好像用到两次了, 节点遍历两次

    class Solution {
    public:
        int TreeDepth(TreeNode* pRoot)
        {
            int rightHigh = 1;
            int leftHigh = 1;
            
            if (nullptr == pRoot) {
                return 0;
            }
            
            if (nullptr != pRoot->left) {
                rightHigh += TreeDepth(pRoot->left);
            }
            
            if (nullptr != pRoot->right) {
                leftHigh += TreeDepth(pRoot->right);
            }
            
            return rightHigh > leftHigh ? rightHigh : leftHigh;
        }
        
        
        bool IsBalanced_Solution(TreeNode* pRoot) {
            if (nullptr == pRoot) {
                return true;
            }
            int left = TreeDepth(pRoot->left);
            int right = TreeDepth(pRoot->right);
            int dif = left - right;
            
            if (dif < -1 || dif >1) {
                return false;
            }
            return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right);
        }
    };
    
  • 相关阅读:
    做才是得到
    常用工具汇总
    迎接2017
    新年礼物
    2017
    asp.net core 日志
    板子|无向图的割点
    11/06信竞快乐模拟赛
    动态规划复习
    894D
  • 原文地址:https://www.cnblogs.com/hesper/p/10499832.html
Copyright © 2011-2022 走看看