zoukankan      html  css  js  c++  java
  • hackerrank Diameter of Binary Tree

    public class DiameterOfTree {   
    public static int diameter = 0; 
    public static int getDiameter(BinaryTreeNode root) {        
        if (root != null) {                     
            int leftCount = getDiameter(root.getLeft());
            int rightCount = getDiameter(root.getRight());
            if (leftCount + rightCount > diameter) {
                diameter = leftCount + rightCount;
                System.out.println("---diameter------------->" + diameter);
            }           
            if ( leftCount > rightCount) {
                return leftCount + 1;
            }
            return rightCount + 1;
        }
        return 0;
      }
    }
    

      

    public static int getDiameter(BinaryTreeNode root) {        
        if (root == null)
            return 0;
    
        int rootDiameter = getHeight(root.getLeft()) + getHeight(root.getRight()) + 1;
        int leftDiameter = getDiameter(root.getLeft());
        int rightDiameter = getDiameter(root.getRight());
    
        return Math.max(rootDiameter, Math.max(leftDiameter, rightDiameter));
    }
    
    public static int getHeight(BinaryTreeNode root) {
        if (root == null)
            return 0;
    
        return Math.max(getHeight(root.getLeft()), getHeight(root.getRight())) + 1;
    }
    

      

  • 相关阅读:
    2014/11/25 函数
    2014/11/24 条件查询
    2、计算器
    1、winform数据库调用(基本方法)
    1、网页基础
    14、函数输出参数、递归
    13、C#简易版 推箱子游戏
    12、函数
    11、结构体、枚举
    10、特殊集合
  • 原文地址:https://www.cnblogs.com/lilyfindjobs/p/4225963.html
Copyright © 2011-2022 走看看