LeetCode,[LeetCode]Balanced Binary Tree

 2023-11-18 阅读 29 评论 0

摘要: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. 思考:求二叉樹高的變形,加上

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 binary tree* struct TreeNode {*     int val;*     TreeNode *left;*     TreeNode *right;*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/
class Solution {
private:bool flag;
public:int DFS(TreeNode *root){if(root){int height1=DFS(root->left);int height2=DFS(root->right);if(abs(height1-height2)>1) flag=false;return max(height1,height2)+1;}else return 0;}bool isBalanced(TreeNode *root) {flag=true;int height=DFS(root);//樹高return flag;}
};

  

轉載于:https://www.cnblogs.com/Rosanna/p/3463596.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/3/175429.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息