zoukankan      html  css  js  c++  java
  • LeetCode 543. Diameter of Binary Tree 二叉树的直径 (C++/Java)

    题目:

    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 the longest 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.

    分析:

    给定一棵二叉树,计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。

    我们定义空结点的直径长度为0,而除root结点外,其余所有结点都有一条边连接其父结点。那么递归求解此问题,当前结点所有的直径长度等于其左右孩子的长度之和,也就是把当前结点当成桥接两个孩子结点的桥梁,更新全局的最大值,但如果当前结点还有父结点的话,则应该是左右孩子的长度取最大值加1,1也就是当前结点连向父结点的那条边,而由于题目规定,我们只能通过一次结点,所以取最大值就好。

    程序:

    C++

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int diameterOfBinaryTree(TreeNode* root) {
            int res = 0;
            dTree(root, res);
            return res;
        }
    private:
        int dTree(TreeNode* root, int& res){
            if(root == nullptr)
                return 0;
            int l = dTree(root->left, res);
            int r = dTree(root->right, res);
            res = max(res, l+r);
            return max(l, r) + 1;
        }
    };

    Java

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public int diameterOfBinaryTree(TreeNode root) {
            res = 0;
            dTree(root);
            return res;
        }
        private int dTree(TreeNode root){
            if(root == null)
                return 0;
            int l = dTree(root.left);
            int r = dTree(root.right);
            res = Math.max(res, l+r);
            return Math.max(l, r) + 1;
        }
        private int res;
    }
  • 相关阅读:
    第一阶段站立会议4
    第一阶段站立会议3
    用户场景描述
    第一阶段站立会议2
    第一阶段站立会议1
    第七周进度条
    第十二周工作总结
    寻找水王
    第十一周工作总结
    构建之法阅读笔记05
  • 原文地址:https://www.cnblogs.com/silentteller/p/12357752.html
Copyright © 2011-2022 走看看