- Maximum Depth of Binary Tree
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
既然是求深度,采用深度优先比较简单。
递归比较重要的一点就是递归退出的条件,对于这道题比较明显,当没有叶子了,即左右指针为空指针时。
考虑这道题的思路,将左叶子节点和右叶子节点分别做为左子树和右子树的根节点,进行递归,当节点不为空时,代表深度加1,为空时,停止递归,深度加0。最后累加结果,取左子树和右子树的最大值,就是最大深度
/**
* 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) return 0;
return 1+max(maxDepth(root->left),maxDepth(root->right));
}
};
2、balanced binary tree
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.
class Solution {
public:
bool isBalanced(TreeNode* root) {
if(!root) return true;
return abs(maxDepth(root->right)-maxDepth(root->left))>1?false:isBalanced(root->right)&&isBalanced(root->left);
}
int maxDepth(TreeNode* root) {
if(!root) return 0;
return 1+max(maxDepth(root->left),maxDepth(root->right));
}
};
这个题是判断平衡二叉树,即每个节点下的左右节子树高度差都不能超过1。
函数直接给出的返回值是bool,为了计量高度就只能另写一个方法,刚好可以用到求每个子树的最大深度,差大于1就返回false,否则递归每一个节点成为子树,判断深度,若判断到最后一个节点,则返回true。