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);
        }
    };
    
  • 相关阅读:
    六、Oracle的数据库管理及数据字典和动态视图
    八、Oracle的数据完整性
    js回调函数
    PL/SQL编程(三)
    四、Oracle的复杂查询
    三、Oracle的简单查询
    C#实现双向链表
    什么是Unix时间戳 [转]
    ANSI escape sequences
    Gibbs Sampling [转]
  • 原文地址:https://www.cnblogs.com/hesper/p/10499832.html
Copyright © 2011-2022 走看看