leetcode 刷题-剑指offer-55题

题目(1)[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)[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/ ↩︎

posted @ 2022-01-24 16:14  发呆鱼  阅读(28)  评论(0)    收藏  举报