欢迎大家阅读参考,如有错误或疑问请留言纠正,谢谢
Balanced Binary Tree
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)自顶向下逐层累加的,而高度是从叶节点开始(其高度为1)自底向上逐层累加的。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { private: bool balance = true; int height(TreeNode *root) { if(!balance) return -1; if(root==NULL) return 0; else { int left_height = height(root->left)+1; int right_height = height(root->right)+1; if( abs(left_height-right_height) > 1) balance = false; else return left_height>right_height ? left_height : right_height; } } public: bool isBalanced(TreeNode *root) { height(root); return balance; } };
时间: 2024-07-30 20:30:36