刷题记录:leetcode543:二叉树的直径

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

示例:

          1
         / \
        2   3
       / \     
      4   5   

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

刚看到题目的时候觉得很简单,不就是递归计算左子树的高度加上右子树的高度嘛,但是这只考虑了路径穿过根节点的情况,对于不穿过根节点的情况,如

          1
         / \
        2   3
       / \     
      4   5 
     /      \
    6       7
              \
               8

应该返回5,路径是[6,4,2,5,7,8],这条路径的根节点是2

所以应该在递归过程中应该维护一个子节点的路径最大值,最后和根节点的路径作比较,结果取两者的最大值。

class Solution {
    int max = 0;
    public int diameterOfBinaryTree(TreeNode root) {
        if(root == null){
            return 0;
        }
        hight(root);
        return max;
    }
    public int hight(TreeNode root){
        if(root == null){
            return 0;
        }
        int hl = hight(root.left);
        int hr = hight(root.right);
        max = Math.max(max, hl+hr);
        return 1+ Math.max(hl, hr);
    }
}

 

posted @ 2020-07-11 22:05  嫩西瓜  阅读(117)  评论(0)    收藏  举报