ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

543. Diameter of Binary Tree

2022-02-05 04:00:26  阅读:127  来源: 互联网

标签:node Binary right tree Tree 543 length root left


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.

标签:node,Binary,right,tree,Tree,543,length,root,left
来源: https://www.cnblogs.com/feiflytech/p/15863790.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有