当前位置: 代码迷 >> 综合 >> 543. Diameter of Binary Tree
  详细解决方案

543. Diameter of Binary Tree

热度:51   发布时间:2023-10-12 12:08:44.0
类型 二叉树的遍历+加一些额外的操作(返回每个节点左右子树的最大深度)

代码

/*** Definition for a binary tree node.* struct TreeNode {* int val;* struct TreeNode *left;* struct TreeNode *right;* };*/
int diameterOfBinaryTree(struct TreeNode* root) {int diameter = 0;if(NULL == root || ( NULL == root->left && NULL == root->right ) ){return 0;}lengestSearch(root,&diameter);return diameter;
}int lengestSearch(struct TreeNode* T,int* diameter){if( NULL == T){return 0;}int leftLen = lengestSearch(T->left,diameter);int rightLen = lengestSearch(T->right,diameter);int lengest = leftLen>rightLen?leftLen:rightLen;*diameter = *diameter>leftLen+rightLen?*diameter:leftLen+rightLen;return lengest+1;
}
思路记录

onedrive

  相关解决方案