Welcome to 发呆鱼.|

发呆鱼

园龄:3年4个月粉丝:1关注:0

leetcode 刷题-剑指offer-55题

题目(1)

输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。

例如:

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

    3
   / \
  9  20
    /  \
   15   7

返回它的最大深度 3 。

解答

新手上路,才学疏浅,望斧正

public class Solution18_1 {
    int res=0;
    public int maxDepth(TreeNode root) {
        if(root==null){
            return 0;
        }

        def(root,0);
        return res;
    }

    public void def(TreeNode node,int h){
        if(node==null){
            return;
        }
        int hight=h+1;
        if(node.right==null && node.left==null){
            res=Math.max(res,hight);
        }
        def(node.right,hight);
        def(node.left,hight);
    }
}

题目(2)

输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。

示例 1:

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

    3
   / \
  9  20
    /  \
   15   7

返回 true

示例 2:

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

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4

返回 false

解答

新手上路,才学疏浅,望斧正

class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root==null){
            return true;
        }else {
            return isBalanced(root.right) && isBalanced(root.left) && Math.abs(nodeHight(root.left)-nodeHight(root.right))<=1;
        }
    }

    public int nodeHight(TreeNode node){
        if(node==null){
            return 0;
        }else {
            return Math.max(nodeHight(node.left),nodeHight(node.right))+1;
        }
    }
}


  1. https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof/ ↩︎

  2. https://leetcode-cn.com/problems/ping-heng-er-cha-shu-lcof/ ↩︎

本文作者:发呆鱼

本文链接:https://www.cnblogs.com/dyiblog/p/15839867.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   发呆鱼  阅读(23)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起