leetcode Balanced Binary Tree

Balanced Binary Tree

My Submissions
Total Accepted: 72116 Total Submissions: 225116 Difficulty: Easy

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.

好吧這個題,就相當於統計深度了。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isBalanced(TreeNode* root) 
{
if (root == NULL)
return true;
return isBalanced(root->left) && isBalanced(root->right) && abs(maxdepth(root->left) - maxdepth(root->right)) <= 1;
}


int maxdepth(TreeNode* root)
{
if (root == NULL)
return 0;
else
return (1 + max(maxdepth(root->left),maxdepth(root->right)));
}
int max(int a, int b)
{
if (a < b)
return b;
else
return a;
}
};

好吧,這個題
發佈了49 篇原創文章 · 獲贊 1 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章