543. Diameter of Binary Tree

2022/2/5 6:12:24

本文主要是介绍543. Diameter of Binary Tree,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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.



这篇关于543. Diameter of Binary Tree的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程