543. 二叉树的直径

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

示例 :
给定二叉树

          1
         / \
        2   3
       / \     
      4   5    

返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。

注意:两结点之间的路径长度是以它们之间边的数目表示。

 

/**
 * 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 {
private:
    int max_diameter;
    int tmp_diameter;

public:
    int diameterOfBinaryTree(TreeNode* root) {
        TreeNode *p = root;
        if(root == NULL) return 0;
        if (root->left == NULL && root->right == NULL) return 0;
        
        PreOrder(p);
        return max_diameter;
    }
    
    int maxDepth(TreeNode* root) {
        if(root == NULL) return 0;
        if (root->left == NULL && root->right == NULL) return 1;
        if (root->left == NULL) return maxDepth(root->right) + 1;
        else if (root->right == NULL) return maxDepth(root->left) + 1;
        else return 1 + max(maxDepth(root->left), maxDepth(root->right));
    }
    
    void PreOrder(TreeNode* T)//先序递归遍历
    {
        if(T!=NULL)
        {            
            tmp_diameter = maxDepth(T->left) + maxDepth(T->right);
            if(tmp_diameter > max_diameter) max_diameter = tmp_diameter;
            PreOrder(T->left);
            PreOrder(T->right);
        }
    }
};

 

posted @ 2019-01-08 15:39  张三编程分享  阅读(411)  评论(0编辑  收藏  举报