当前位置: 代码迷 >> 综合 >> 【leetcode】110. 平衡二叉树
  详细解决方案

【leetcode】110. 平衡二叉树

热度:26   发布时间:2024-02-12 06:10:43.0

题目描述:110. 平衡二叉树

思路:

左右子树高度差小于等于1,则平衡,先求高度,再判断是否平衡。递归实现。

易错点在于判断完root是否平衡还要判断root左右孩子节点。

实现代码:

/*** 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) return true;int t = abs(idepth(root->left)-idepth(root->right));if(t==0 || t == 1) return isBalanced(root->left) && isBalanced(root->right);else return false;}int idepth(TreeNode* root){if(!root) return 0;return max(idepth(root->left), idepth(root->right))+1;}
};

参考链接