二叉树最长连续序列
public class Solution {
public int max = 1;
/**
* @param root: the root of binary tree
* @return: the length of the longest consecutive sequence path
*/
public int longestConsecutive(TreeNode root) {
// write your code here
if(root == null){
return 0;
}
childNode(root, 1);
return max;
}
public void childNode(TreeNode node, int n){
if(node == null){
return;
}
if(node.left != null && node.left.val - node.val == 1){
int left = n + 1;
max = Math.max(max, left);
childNode(node.left,left);
}else{
childNode(node.left, 1);
}
if(node.right != null && node.right.val - node.val == 1){
int right = n + 1;
max = Math.max(max, right);
childNode(node.right,right);
}else{
childNode(node.right, 1);
}
}
}
复制代码
解题思路:
首先不断下移左右子节点, 如果子节点的val - 父节点的val 等于 1那么说明连续,则节点数加1, 同时比目前的最大节点数max比较,取最大值