Loading

【leetcode】543. Diameter of Binary Tree

  Given the root of a binary tree, return 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. The length of a path between two nodes is represented by the number of edges between them.

  

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int res=0;
    int digui(TreeNode* root)
    {
        int left_len=0,right_len=0;
        if(root->left!=NULL){
            left_len=digui(root->left)+1;
        }
        if(root->right!=NULL){
            right_len=digui(root->right)+1;
        }
        res=max(res,left_len+right_len);
        return max(left_len,right_len);
    }
    int diameterOfBinaryTree(TreeNode* root) {
        //这题目做过 为啥再做就感觉还是不会呢?考点遍历这个二叉树 同时统计长度 计算长度 然后左右相加
        //考察递归的写法
        if (root!=NULL){
            digui(root);
        }
        return res;
    }
};

 

posted @ 2021-11-20 14:46  aalanwyr  阅读(29)  评论(0编辑  收藏  举报