二叉树的直径,即二叉树的节点之间最大距离

来源:互联网 发布:工业组态软件 编辑:程序博客网 时间:2024/06/05 16:44

问题:如题,求解树的直径,即树中两个节点的最长路径距离,该路径可能经过根节点,也可能不经过根节点

该题也是leetcode上的题,代码如下。

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */class Solution {    int res = 0;    public int diameterOfBinaryTree(TreeNode root) {        if(root == null)            return 0;        getHeight(root);        return res;    }    public int getHeight(TreeNode node){        if(node == null)            return 0;        int left = getHeight(node.left);        int right = getHeight(node.right);        res = Math.max(res, left+right);        return 1+Math.max(left, right);    }}
原创粉丝点击