標籤:style blog color 使用 io for ar div 代碼
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. 空樹是一顆平衡二叉樹
2. 它的左子樹和右子樹的高度差不超過1
3. 它的左子樹和右子樹也是平衡二叉樹
故判斷這棵樹是否是平衡二叉樹,不僅要求樹的高度,也要判斷左右子樹是否均為平衡二叉樹,使用樹的後序遍曆,求樹高度的時候同時判斷這棵樹是否是平衡二叉書,代碼如下:
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */10 class Solution {11 public:12 bool isBalanced(TreeNode *root) {13 return getdepth(root) > -1;14 }15 16 int getdepth(TreeNode* root) { //返回正常高度,說明是平衡二叉樹,否則返回-117 if( !root ) return 0; //空樹是平衡二叉樹,返回018 int leftdepth = getdepth(root->left); //左子樹高度19 int rightdepth = getdepth(root->right); //右子樹高度20 //左子樹不是 或 右子樹不是 或 左右子樹高度差超過121 if( leftdepth == -1 || rightdepth == -1 || abs(leftdepth-rightdepth) > 1 ) return -1;22 return max(leftdepth, rightdepth)+1;23 }24 };
Balanced Binary Tree