1.问题:给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/diameter-of-binary-tree
示例 :
给定二叉树
1 / \ 2 3 / \ 4 5
返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]
思路:二叉树的直径不一定过根节点,因此需要去搜一遍所有子树(例如root,root->left,root->right...为根节点的树)对应的直径,取最大值。
root的直径 = root左子树高度 + root右子树高度
root的高度 = max {root左子树高度, root右子树高度} + 1
/** * 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 res=0;//最大直径,预设为0 int diameterOfBinaryTree(TreeNode* root) { depth(root); return res; } int depth(TreeNode* root) { if(root==NULL) return 0; int left=depth(root->left);//左子树深度 int right=depth(root->right);//右子树深度 res=max(res,left+right);//计算左右深度再加1 return max(left,right)+1;//返回最深的深度 } };
2.