程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> Balanced Binary Tree

Balanced Binary Tree

編輯:關於C++

description link example solution 1 explanation for solution 1 solution 2 explanation for soluton 2

description

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.

 

example

Given binary tree A={3,9,20,#,#,15,7}, B={3,#,20,15,7}

A) 3 B) 3
/
9 20 20
/ /
15 7 15 7

The binary tree A is a height-balanced binary tree, but B is not.

solution 1

    bool isBalancedTree(TreeNode *root,int &depth) {
    if(root == NULL) {
     return true;
    }
    int leftDepth = 0;
    bool leftResult = isBalancedTree(root->left, leftDepth);
    if(!leftResult) {
       return false;
    }
    int rightDepth = 0;
    bool rightResult = isBalancedTree(root->right, rightDepth);
    if(!rightResult) {
       return false;
    }
    if(abs(leftDepth-rightDepth) >= 2) {
       return false;
    }
    depth=(leftDepth>rightDepth)?(leftDepth+depth+1):(rightDepth+depth+1);
    return true;
}
 bool isBalanced(TreeNode *root) {
        // write your code here
     int depth=0;
      return isBalancedTree(root ,depth);
    }

explanation for solution 1

balanced tree 滿足三個條件:左右子樹都是,高度差小於2
既要求高度又要加判斷,所以必須用到引用

solution 2

public:
    int max(int i,int j) {
    return i > j?i:j;
    }
    int getDepth(TreeNode *root) {
    if (root == NULL) {
        return 0;
    }
    int leftDepth = getDepth(root->left);
    int rightDepth = getDepth(root->right);
    if (leftDepth == -1 || rightDepth == -1 || abs(leftDepth-rightDepth) > 1) {
        return -1;
    }
    return max(leftDepth,rightDepth) + 1;
   }

    /**
     * @param root: The root of binary tree.
     * @return: True if this Binary tree is Balanced, or false.
     */
    bool isBalanced(TreeNode *root) {
        // write your code here
        return getDepth(root) != -1;
    }

explanation for soluton 2

用返回值是-1來給出子序列是否是balanced tree,更加巧妙

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved