• 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.

    题解:

    与minimum代码几乎完全一样,只需要修改math.min为math.max

    public class Solution {
        public int maxDepth(TreeNode root) {
            if (root == null) {
                return 0;
            }
            return getMin(root);
        }
    
        public int getMin(TreeNode root){
            if (root == null) {
                return Integer.MIN_VALUE;
            }
    
            if (root.left == null && root.right == null) {
                return 1;
            }
    
            return Math.max(getMin(root.left), getMin(root.right)) + 1;
        }
    }

     用divide and conquer

    public class Solution {
        public int maxDepth(TreeNode root) 
        {
            if (root==null) return 0;
            int left=maxDepth(root.left);
            int right=maxDepth(root.right);
            return Math.max(left,right)+1;
            
        }
    }
  • 相关阅读:
    设计模式总结
    设计模式之工厂
    C#
    UML画图总结
    UML视频总结
    类图
    读取文件信息
    HMAC算法加密
    SHA_1计算消息摘要
    获取指定长度的随机字符串
  • 原文地址:https://www.cnblogs.com/hygeia/p/4703660.html
Copyright © 2020-2023  润新知