LeetCode 110. 平衡二叉树

it2022-05-05  154

给定一个二叉树,判断它是否是高度平衡的二叉树。

本题中,一棵高度平衡二叉树定义为:

一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。

示例 1:

给定二叉树 [3,9,20,null,null,15,7]

返回 true 。示例 2:

给定二叉树 [1,2,2,3,3,null,null,4,4]

返回 false 。

算法:递归判断即可。

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

 

转载于:https://www.cnblogs.com/programyang/p/11166938.html

相关资源:各显卡算力对照表!

最新回复(0)