首页 > 其他 > 详细

543. 二叉树的直径

时间:2020-03-24 13:50:10      阅读:54      评论:0      收藏:0      [点我收藏+]
 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 //二叉树的直径只有两种情况:经过根节点和不经过根节点
11 class Solution 
12 {
13 public:
14     int diameterOfBinaryTree(TreeNode* root) 
15     {
16         if(root == NULL || root->left == 0 && root->right == 0) return 0;
17         int a = depth(root->left) != 0 ? depth(root->left) - 1 : 0;//看是否有左子树
18         int b = depth(root->right) != 0 ? depth(root->right) - 1: 0;//看是否有右子树
19 
20         if(root->left == 0 && root->right != 0) return b + 1;//只有右子树,一定会经过根节点
21         else if(root->left != 0 && root->right == 0) return a + 1;//只有左子树,一定会经过根节点
22         else return max(a + b + 2,max(diameterOfBinaryTree(root->left),diameterOfBinaryTree(root->right)));//经过根节点与不经过根节点求最大值
23         //a + b + 2——>经过根节点
24         //max(diameterOfBinaryTree(root->left),diameterOfBinaryTree(root->right))——>不经过根节点
25     }
26 
27     int depth(TreeNode* root)//求二叉树的深度
28     {
29         if(root == NULL) return 0;
30         if(root->left == 0 && root->right == 0) return 1;
31         return max(depth(root->left),depth(root->right)) + 1;
32     }
33 };

 

543. 二叉树的直径

原文:https://www.cnblogs.com/yuhong1103/p/12558301.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!