leetcode104&110

  1. 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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值