Tuesday, July 12, 2016

298. Binary Tree Longest Consecutive Sequence

Problem:
Given a binary tree, find the length of the longest consecutive sequence path. The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The longest consecutive path need to be from parent to child (cannot be the reverse).
For example, [1,null,3,2,4,null,null,null,5]. The longest consecutive sequence is [3,4,5], so length is 3.
Another example, [2,null,3,2,null,1,null]. The longest consecutive sequence is [2,3], not [3,2,1].

A typical dfs solution. The dfs function needs to have parent node and consecutive length so far as input. Why parent node but not check child node for current node? With parent node, the code will be more concise to avoid many corner case, such as what if left is null but right is not and vice versa. The maximum consecutive length will be based on the consecutive length so far.

1:  /**  
2:   * Definition for a binary tree node.  
3:   * struct TreeNode {  
4:   *   int val;  
5:   *   TreeNode *left;  
6:   *   TreeNode *right;  
7:   *   TreeNode(int x) : val(x), left(NULL), right(NULL) {}  
8:   * };  
9:   */  
10:  class Solution {  
11:  public:  
12:    int longestConsecutive(TreeNode* root) {  
13:      return dfs(root, NULL, 0);  
14:    }  
15:    int dfs(TreeNode *root, TreeNode *parent, int len) {  
16:      if (root == NULL) return len;  
17:      len = (parent && root->val == parent->val+1) ? len+1 : 1;  
18:      return max(len, max(dfs(root->left, root, len), dfs(root->right, root, len)));  
19:    }  
20:  };  

No comments:

Post a Comment