输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
示例
给定二叉树 [3,9,20,null,null,15,7]
返回它的最大深度 3 。
代码如下(示例):
/**
* 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 getDepth(TreeNode* node){
if (node == NULL) return 0;
int leftdepth = getDepth(node -> left);
int rightdepth = getDepth(node -> right);
int depth = max(leftdepth,rightdepth) + 1;
return depth;
}
int maxDepth(TreeNode* root) {
return getDepth(root);
}
};
代码如下(示例):
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == NULL) return 0;
return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
};
代码如下(示例):
class Solution {
public:
int maxDepth(TreeNode* root) {
queue<TreeNode*> que;
if (root == NULL) return 0;
if (root != NULL) que.push(root);
int level = 0;
while (que.empty() == false){
int size = que.size();
for (int i = 0; i < size; i++){
TreeNode* tem = que.front();
que.pop();
if (tem -> left != NULL) que.push(tem -> left);
if (tem -> right != NULL) que.push(tem -> right);
}
level++;
}
return level;
}
};
示例1
输入:root = [3,9,20,null,null,15,7]
输出:true
示例2
输入:root = [1,2,2,3,3,null,null,4,4]
输出:false
class Solution {
public:
int getheight(TreeNode* node){
if (node == nullptr) return 1;
int leftheight = getheight(node -> left);
int rightheight = getheight(node -> right);
int height = max(leftheight,rightheight) + 1;
return height;
}
bool isBalanced(TreeNode* root) {
if (root == nullptr) return true;
else return abs(getheight(root -> left)-getheight(root -> right)) <= 1 && isBalanced(root -> left) && isBalanced(root -> right);
}
};