当前位置:网站首页>[sword finger offer] interview question 55 - Ⅰ / Ⅱ: depth of binary tree / balanced binary tree
[sword finger offer] interview question 55 - Ⅰ / Ⅱ: depth of binary tree / balanced binary tree
2022-07-27 15:52:00 【Jocelin47】
The finger of the sword Offer 55 - I. The depth of the binary tree
Method 1 :
/** * 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:
int maxDepth(TreeNode* root) {
if(root == nullptr )
return 0;
return max( maxDepth(root->left), maxDepth(root->right)) + 1;
}
// int maxDepth(TreeNode* root)
// {
// if( root == nullptr )
// return 0;
// int lefHeight = maxDepth(root->left);
// int rightHeight = maxDepth(root->right);
// return (lefHeight > rightHeight) ? lefHeight + 1 : rightHeight + 1;
// }
};
The finger of the sword Offer 55 - II. Balanced binary trees
Method 1 : recursive
/** * 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 == nullptr )
return true;
if( abs( Depth(root->left) - Depth(root->right) ) > 1 )
return false;
return isBalanced(root->left) && isBalanced(root->right);
}
int Depth(TreeNode* root) {
if(root == nullptr )
return 0;
return max( Depth(root->left), Depth(root->right)) + 1;
}
// int Depth(TreeNode* root)
// {
// if( root == nullptr )
// return 0;
// int lefHeight = Depth(root->left);
// int rightHeight = Depth(root->right);
// return (lefHeight > rightHeight) ? lefHeight + 1 : rightHeight + 1;
// }
};
Method 2 :
边栏推荐
猜你喜欢
随机推荐
禁令之下,安防巨头海康与大华的应对之策!
CAS compares the knowledge exchanged, ABA problems, and the process of lock upgrading
C语言:扫雷小游戏
【剑指offer】面试题53-Ⅱ:0~n-1中缺失的数字——二分查找
【剑指offer】面试题53-Ⅰ:在排序数组中查找数字1 —— 二分查找的三个模版
【剑指offer】面试题55 - Ⅰ/Ⅱ:二叉树的深度/平衡二叉树
语音直播系统——提升云存储安全性的必要手段
【云享读书会第13期】视频文件的编码格式
Go language learning notes (1)
C language: data storage
[sword finger offer] interview question 45: arrange the array into the smallest number
[sword finger offer] interview question 41: median in data flow - large and small heap implementation
网络设备硬核技术内幕 路由器篇 小结(下)
【剑指offer】面试题52:两个链表的第一个公共节点——栈、哈希表、双指针
[TensorBoard] OSError: [Errno 22] Invalid argument处理
[Yunxiang book club issue 13] coding format of video files
Binder初始化过程
复杂度分析
C:什么是函数中的返回值(转)
初识结构体








