美文网首页
Balanced Binary Tree - 平衡树

Balanced Binary Tree - 平衡树

作者: 郑明明 | 来源:发表于2016-10-31 14:14 被阅读29次
    • 如题:
      Given a binary tree, determine if it is height-balanced.
      For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
      平衡树的定义就是对于每一个节点,他的两棵子树的深度之差不能大于1

    • 思路:
      这道题算的上是比较简单的了,思路大概就是两层:

      1. 递归判断每个节点
      2. 具体判断是每个节点的两个子树的深度比较
    • 解题:

        bool isBalanced(TreeNode* root) {
            TreeNode *tempTreeNode = root;
            if (tempTreeNode == NULL) {
                return true;
            }
            if (abs(getMaxDeepth(tempTreeNode->left) - getMaxDeepth(tempTreeNode->right)) > 1) {
                return false;
            }
            return isBalanced(tempTreeNode->left) && isBalanced(tempTreeNode->right);
        }
        
        int getMaxDeepth(TreeNode *treeNode) {
            if (treeNode == NULL) {
                return 0;
            }
            int left = getMaxDeepth(treeNode->left);
            int right = getMaxDeepth(treeNode->right);
            return (left > right ? left : right) + 1;
        }
    

    相关文章

      网友评论

          本文标题:Balanced Binary Tree - 平衡树

          本文链接:https://www.haomeiwen.com/subject/jnkputtx.html