This is a Post Order binary tree problem. For every node, we need to know its left tree's maximal diameter and its right tree's maximal diameter, and add left and right, we can get a sub-tree's maximal diameter, we just find the maximum of all node, the problem will be solved.

When try to solve this problem, we need to consider:

1. If the node is a leaf node, the lengh is 0.

2. if the node's left is not null, the node's left length should be left tree's maximal length +1.

3. if the node's right is not null, the node's right length should be right tree's maximal length +1.

4. the sub-tree's length left length+right length.

5. For every node, we can only return the maximum of left length or right length.

The solution is as following, time complexity is O(n):

    private int res = 0;
    public int diameterOfBinaryTree(TreeNode root) {
        postOrder(root);
        return res;
    }
    
    private int postOrder(TreeNode root){
         if(root.left==null && root.right==null) //1. if it's leaf node, return 0
            return 0;
        int left=0, right = 0;
        if(root.left!=null){
            left = postOrder(root.left)+1;     //2.if the node's left is not null, the node's length should be left tree's maximal length +1.
        }
        if(root.right!=null){
            right = postOrder(root.right)+1; //3.if the node's right is not null, the node's right length should be right tree's maximal length +1.
        }
        res = Math.max(res, left+right);  4.the sub-tree's length left length+right length.
        return Math.max(left, right);  5. For every node, we can only return the maximum of left length or right length.
    }

 We can expand the solution from binary tree to all trees, which is : 1522. Diameter of N-Ary Tree.

posted on 2022-02-05 03:31  阳光明媚的菲越  阅读(22)  评论(0编辑  收藏  举报