543 Diameter of Binary Tree

Given a binary tree, you need to calculate its diameter length. The diameter of a binary tree is the maximum of the path lengths of any two nodes. This path may pass through the root node.
Example:
Given a binary tree
          1
         / \
        2 3
       / \     
      4 5    
returns 3, whose length is the path [4,2,1,3] or [5,2,1,3].
Note: The length of the path between two nodes is expressed as the number of edges between them.
See: https://leetcode.com/problems/diameter-of-binary-tree/description/

C++:

method one:

class Solution {
public:
    int diameterOfBinaryTree(TreeNode* root)
    {
        int res = 0;
        maxDepth(root, res);
        return res;
    }
    int maxDepth(TreeNode* node, int& res)
    {
        if (!node)
        {
            return 0;
        }
        int left = maxDepth(node->left, res);
        int right = maxDepth(node->right, res);
        res = max(res, left + right);
        return max(left, right) + 1;
    }
};

 Method Two:

/**
 * 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;
        maxDepth(root,res);
        return res;
    }
    int maxDepth(TreeNode* node,int &res)
    {
        if(!node)
        {
            return 0;
        }
        if(m.count(node))
        {
            return m[node];
        }
        int left=maxDepth(node->left,res);
        int right=maxDepth(node->right,res);
        res=max(res,left+right);
        return m[node]=(max(left,right)+1);
    }
private:
    unordered_map<TreeNode*,int> m;
};

 Reference: http://www.cnblogs.com/grandyang/p/6607318.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324715306&siteId=291194637