543. Diameter of Binary Tree

来源:互联网 发布:淘宝为啥不能提交订单 编辑:程序博客网 时间:2024/06/06 03:01

1.题目

   

Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of thelongest path between any two nodes in a tree. This path may or may not pass through the root.

Example:
Given a binary tree 

          1         / \        2   3       / \           4   5    

Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

Note: The length of path between two nodes is represented by the number of edges between them.

2.分析

   涉及到树形结构的算法题,一般都可以考虑用递归的方法解题,当然前提是对于时间复杂度要求不严格的情况下,这道题有三种情况,根节点只有左子树,只有右子树,左右子树都有。而本题的意思也很明确,就是找左子树->根节点->右子树最长路径,若进行递归,要对三种情况取最大值,本题中所说的最长路径就是指子树的深度,所以,你需要写一个返回树深度的方法,也是递归实现。

3.解题

public class Solution {
    public int diameterOfBinaryTree(TreeNode root) {
        // 因为树本身是递归定义,所以解树形结构的题,很多采用递归的解法。
        //
        if(root==null){
            return 0;
        }
        int left = diameterOfBinaryTree(root.left);
        
        int right = diameterOfBinaryTree(root.right);
        
        int number = treeLength(root.left)+treeLength(root.right);
        
        return Math.max(number,Math.max(left,right));
    }
    public int treeLength(TreeNode node){
        if(node==null){
            return 0;
        }
        return Math.max(treeLength(node.left),treeLength(node.right))+1;
    }
    
}

4.总结

   最开始,我考虑用递归找最长路径,但是对于树的深度,我尝试用辅助栈实现,发现一直有没有考虑的情况,按道理是可以实现的,只是一开始解题,没有想明白,但思路是对的,没错。

原创粉丝点击