leetcode 543.二叉树的直径

整体思路:其实就是对于树的每一个结点的左右子树相加,看看哪个结点的直径最大而已。

有人会认为只有经过根的那条路径才是最长的直径,其实不然,我们需要考虑更周到一点才行,只有遍历全部结点才能确定。

实现一:用递归实现

用两个函数,一个函数用来获取当前结点的深度,一个函数用来遍历树的结点。这里的遍历方式采用了前序遍历。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    int maxs=0;
    public int diameterOfBinaryTree(TreeNode root) {
        if(root==null)
        return 0;
        qianxu(root);
        return maxs;
    }
    public int getHeight(TreeNode t,int cnt){
        if(t==null)
        return cnt;
        cnt++;
        return Math.max(getHeight(t.right,cnt),getHeight(t.left,cnt));
    }
    public void qianxu(TreeNode t){
        if(t==null)
        return;
        int res=getHeight(t.left,0)+getHeight(t.right,0);
        maxs=Math.max(res,maxs);
        qianxu(t.left);
        qianxu(t.right);
    }
}

实现二:DFS

这种方法其实就是把递归中的两个函数合在一起使用了,这样大大降低了时间复杂度。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    int maxs=0;
    public int diameterOfBinaryTree(TreeNode root) {
        if(root==null)
        return 0;
        dfs(root);
        return maxs;
    }
    public int dfs(TreeNode t){
        if(t==null)
        return 0;
        int l=dfs(t.left);
        int r=dfs(t.right);
        maxs=Math.max(maxs,l+r);
        return Math.max(l,r)+1;
    }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值