类型 二叉树的遍历+加一些额外的操作(返回每个节点左右子树的最大深度)
代码
/*** 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