• Leetcode 543.二叉树的直径


    二叉树的直径

    给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。

    示例 :
    给定二叉树

    1

    /

    2 3

    /

    4 5

    返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。

    注意:两结点之间的路径长度是以它们之间边的数目表示。

     

     

    思路:先用的方法是只计算根节点的左右节点的高度,然后返回两个数相加的和,但是发现有些情况并没有通过,是因为可能最长路径并不是通过根节点的,例如左孩子只有一个节点,但是右孩子的左右节点都很多,所以最后的方法是在计算二叉树的高度的时候比较左右子节点的高度的和与当前最长路径比较,最后返回最长路径。

     

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     int maxNum = 0;
    12 
    13     public int diameterOfBinaryTree(TreeNode root) {
    14         int n = 0;
    15         if (root == null || (root.left == null && root.right == null)) {
    16             return 0;
    17         }
    18         helper(root);
    19         return maxNum;
    20     }
    21 
    22     public int helper(TreeNode root) {
    23         if (root == null) {
    24             return 0;
    25         }
    26         int left = helper(root.left);
    27         int right = helper(root.right);
    28         if (left + right > maxNum) {
    29             maxNum = left + right;
    30         }
    31         return left > right ? left + 1 : right + 1;
    32 
    33     }
    34 }
  • 相关阅读:
    [Leetcode] Swap Nodes in Pairs
    [Leetcode] Roman to Integer
    [Leetcode] Search Insert Position
    [Leetcode] String to Integer (atoi)
    [Leetcode] Count and Say
    [Leetcode] Valid Palindrome
    [Leetcode] Implement strStr()
    一起手写吧!防抖和节流
    CSS系列,清除浮动方法总结
    css系列,选择器权重计算方式
  • 原文地址:https://www.cnblogs.com/kexinxin/p/10373958.html
Copyright © 2020-2023  润新知