描述
给一棵二叉树,找到最长连续路径的长度。
这条路径是指 任何的节点序列中的起始节点到树中的任一节点都必须遵循 父-子 联系。最长的连续路径必须是从父亲节点到孩子节点(不能逆序
)。
您在真实的面试中是否遇到过这个题?
是
样例
举个例子:
1
\
3
/ \
2 4
\
5
最长的连续路径为 3-4-5
,所以返回 3
。
2
\
3
/
2
/
1
最长的连续路径为 2-3
,而不是 3-2-1
,所以返回 2
。
先序遍历左子树即可。
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: the root of binary tree
* @return: the length of the longest consecutive sequence path
*/
int longestConsecutive(TreeNode * root) {
// write your code here
return lengthcal(root,NULL,0);
}
int lengthcal(TreeNode * root,TreeNode * parent,int lengthwitgoutroot){
if(root==NULL) return 0;
int length=(parent!=NULL&&parent->val+1==root->val)?lengthwitgoutroot+1:1;
int left=lengthcal(root->left,root,length);
int right=lengthcal(root->right,root,length);
return max(length,max(left,right));
}
};