LeetCode110. Balanced Binary Tree(C++实现)

LeetCode110. Balanced Binary Tree(C++实现)

题目链接

Balanced Binary Tree

AC代码

/*** Definition for a binary tree node.* struct TreeNode {*     int val;*     TreeNode *left;*     TreeNode *right;*     TreeNode() : val(0), left(nullptr), right(nullptr) {}*     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}*     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}* };*/
class Solution {
public:bool flag;int postOrderTraverse(TreeNode *p) {if (!flag) {return 0;}if (!p) {return 0;}if (!p->left && !p->right) {return 1;}int left = postOrderTraverse(p->left);int right = postOrderTraverse(p->right);if (abs(left - right) > 1) {flag = false;}return 1 + max(left, right);}bool isBalanced(TreeNode* root) {if (!root) {return true;}flag = true;postOrderTraverse(root);return flag;}
};

算法思路

判断给定二叉树是否为平衡二叉树,根据平衡二叉树定义,平衡二叉树任意节点的左右子树高度差小于1,后序遍历,递归到叶子节点时,返回树高1,其父亲节点判断左右子树树高差距,若大于1,置flag为false,否则返回左右子树树高较高者加1,为当前子树树高

样例输入1

[3,9,20,null,null,15,7]

样例输出1

true

样例输入2

[1,2,2,3,3,null,null,4,4]

样例输出2

false

鸣谢

LeetCode

最后

  • 由于博主水平有限,不免有疏漏之处,欢迎读者随时批评指正,以免造成不必要的误解!