Leetcode OJ contest24 543 Diameter of Binary Tree

来源:互联网 发布:淘宝店铺改名字怎么改 编辑:程序博客网 时间:2024/06/05 18:26
/**
 * 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 maxdiadepth=0;
    int dfs(TreeNode* root){
        if(root==NULL)
            return 0;
        int leftdepth=dfs(root->left);
        int rightdepth=dfs(root->right);
        if(leftdepth+rightdepth>maxdiadepth)
            maxdiadepth=leftdepth+rightdepth;
        return max(leftdepth+1,rightdepth+1);
    }
    int diameterOfBinaryTree(TreeNode* root) {
        dfs(root);
        return maxdiadepth;
    }
};
0 0
原创粉丝点击