LeetCode 549 - Binary Tree Longest Consecutive Sequence II
http://shibaili.blogspot.com/2015/10/day-131-288-unique-word-abbreviation.html
X. PreOrder Java
Simple Recursive DFS without global variable
https://discuss.leetcode.com/topic/29205/simple-recursive-dfs-without-global-variable
http://algobox.org/binary-tree-longest-consecutive-sequence/
https://leetcode.com/discuss/68723/simple-recursive-dfs-without-global-variable
X. BFS
https://www.programcreek.com/2014/04/leetcode-binary-tree-longest-consecutive-sequence-java/
http://algobox.org/binary-tree-longest-consecutive-sequence/
https://discuss.leetcode.com/topic/28269/two-simple-iterative-solutions-bfs-and-dfs
Related:
题目: find Longest Consective Increasing Sequence in Binary Tree from root
public class LICSinBinaryTree {
public int getLICSinBT(TreeNode root) {
if(root == null) {
return 0;
}
List<Integer> list = new ArrayList<Integer>();
list.add(Integer.MIN_VALUE);
helper(root, root.left, 1, list);
helper(root, root.right, 1, list);
return list.get(0);
}
public void helper(TreeNode pre, TreeNode cur, int num, List<Integer> list) {
if(cur == null || cur.val <= pre.val) {
if(num > list.get(0)) {
list.add(0, num);
}
return;
}
helper(cur, cur.left, num+1, list);
helper(cur, cur.right, num+1, list);
}
}
http://www.szeju.com/index.php/other/35241410.html
private int longest = 0; public int longestConsecutive(TreeNode root) { helper(root); return longest; } private int helper(TreeNode root) { if (root == null) { return 0; } int left = helper(root.left); int right = helper(root.right); int subtreeMax = 1; if (root.left != null && root.val + 1 == root.left.val) { subtreeMax = Math.max(left + 1, subtreeMax); } if (root.right != null && root.val + 1 == root.right.val) { subtreeMax = Math.max(right + 1, subtreeMax); } longest = Math.max(subtreeMax, longest); return subtreeMax; }
http://www.cnblogs.com/grandyang/p/5252599.html
下面这种写法是利用分治法的思想,对左右子节点分别处理,如果左子节点存在且节点值比其父节点值大1,则递归调用函数,如果节点值不是刚好大1,则递归调用重置了长度的函数,对于右子节点的处理情况和左子节点相同
https://github.com/YaokaiYang-assaultmaster/LeetCode/blob/master/LeetcodeAlgorithmQuestions/298.%20Binary%20Tree%20Longest%20Consecutive%20Sequence.md
https://xuezhashuati.blogspot.com/2017/03/lintcode-595-binary-tree-longest.html
用分治法遍历整个树。同时维护一个最长序列的变量longest。
遍历每个节点的时候,测试一下加上这个节点的最长序列是多少,决定是否要更新longest。
遍历完整棵树,longest就是我们求的值。
http://www.1point3acres.com/bbs/thread-210141-1-1.html
一些空间放不下的follow up
Google Interview - Longest Continuous Path of Tree - 我的博客 - ITeye技术网站
给一个树root的pointer,树包含多个分支,树结构要自己创造。求一条最长路径。
例如(括号对应上面node)
树: 2
| | | |
5 7 3 6
(| | )( | )( | ) (| |)
6 3 2 4 5 8
|
3
返回3因为 (2-3-4) 这条线。优化要求时间O(n)
http://shibaili.blogspot.com/2015/10/day-131-288-unique-word-abbreviation.html
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 \ 3 / \ 2 4 \ 5Longest consecutive sequence path is
3-4-5
, so return 3
.2 \ 3 / 2 / 1Longest consecutive sequence path is
2-3
,not3-2-1
, so return 2
.Simple Recursive DFS without global variable
public int longestConsecutive(TreeNode root) { return getLongestConsecutive(root, null, 0); } private int getLongestConsecutive(TreeNode child, TreeNode parent, int len) { if (child == null) return 0; len = (parent != null && parent.val == child.val - 1) ? len + 1 : 1; return Math.max(len, Math.max( getLongestConsecutive(child.left, child, len), getLongestConsecutive(child.right, child, len) ) ); }
public int longestConsecutive(TreeNode root) {
return (root==null)?0:Math.max(dfs(root.left, 1, root.val), dfs(root.right, 1, root.val));
}
public int dfs(TreeNode root, int count, int val){
if(root==null) return count;
count = (root.val - val == 1)?count+1:1;
int left = dfs(root.left, count, root.val);
int right = dfs(root.right, count, root.val);
return Math.max(Math.max(left, right), count);
}
https://discuss.leetcode.com/topic/50962/concise-java-recursive-solution-without-static-variable public int longestConsecutive(TreeNode root) {
if(root == null) return 0;
return helper(root, 0, root.val);
}
// currLen is the length of longest consecutive path ending with node n's parent
private int helper(TreeNode n, int currLen, int expect) {
if (n == null) return 0;
currLen = n.val == expect ? currLen+1 : 1;
return Math.max(currLen,
Math.max(helper(n.left, currLen, n.val+1), helper(n.right, currLen, n.val+1)));
}
http://www.chenguanghe.com/binary-tree-longest-consecutive-sequence/
private int result = Integer.MIN_VALUE;
public int longestConsecutive(TreeNode root) {
if(root == null)
return 0;
dfs(root, 0, root);
return result;
}
private void dfs(TreeNode root, int cur, TreeNode pre) {
if(root == null)
return;
if(root.val == pre.val+1)
cur++;
else
cur = 1;
result = Math.max(result, cur);
dfs(root.left, cur, root);
dfs(root.right, cur, root);
}
https://leetcode.com/discuss/66584/easy-java-dfs-is-there-better-time-complexity-solution
public int longestConsecutive(TreeNode root) {
int[] ans = new int[1];
dfs(root, 0, 0, ans);
return ans[0];
}
public void dfs(TreeNode root, int length, int target, int[] ans) {
if (root == null) return;
length = root.val == target ? length + 1 : 1;
dfs(root.left, length, root.val + 1, ans);
dfs(root.right, length, root.val + 1, ans);
ans[0] = Math.max(length, ans[0]);
}
Python Iterative Depth-First Searchhttp://algobox.org/binary-tree-longest-consecutive-sequence/
def longestConsecutive(self, root):
if not root:
return 0
ans, stack = 0, [[root, 1]]
while stack:
node, length = stack.pop()
ans = max(ans, length)
for child in [node.left, node.right]:
if child:
l = length + 1 if child.val == node.val + 1 else 1
stack.append([child, l])
return ans
http://www.cnblogs.com/jcliBlogger/p/4923745.html12 int longestConsecutive(TreeNode* root) { 13 return longest(root, NULL, 0); 14 } 16 int longest(TreeNode* now, TreeNode* parent, int len) { 17 if (!now) return len; 18 len = (parent && now->val == parent->val + 1) ? len + 1 : 1; 19 return max(len, max(longest(now->left, now, len), longest(now->right, now, len))); 20 }http://segmentfault.com/a/1190000003957798
https://leetcode.com/discuss/68723/simple-recursive-dfs-without-global-variable
因为要找最长的连续路径,我们在遍历树的时候需要两个信息,一是目前连起来的路径有多长,二是目前路径的上一个节点的值。我们通过递归把这些信息代入,然后通过返回值返回一个最大的就行了。这种需要遍历二叉树,然后又需要之前信息的题目思路都差不多,比如Maximum Depth of Binary Tree和Binary Tree Maximum Path Sum。
public int longestConsecutive(TreeNode root) {
if(root == null){
return 0;
}
return findLongest(root, 0, root.val - 1);
}
private int findLongest(TreeNode root, int length, int preVal){
if(root == null){
return length;
}
// 判断当前是否连续
int currLen = preVal + 1 == root.val ? length + 1 : 1;
// 返回当前长度,左子树长度,和右子树长度中较大的那个
return Math.max(currLen, Math.max(findLongest(root.left, currLen, root.val), findLongest(root.right, currLen, root.val)));
}
https://www.programcreek.com/2014/04/leetcode-binary-tree-longest-consecutive-sequence-java/
public int longestConsecutive(TreeNode root) { if(root==null) return 0; LinkedList<TreeNode> nodeQueue = new LinkedList<TreeNode>(); LinkedList<Integer> sizeQueue = new LinkedList<Integer>(); nodeQueue.offer(root); sizeQueue.offer(1); int max=1; while(!nodeQueue.isEmpty()){ TreeNode head = nodeQueue.poll(); int size = sizeQueue.poll(); if(head.left!=null){ int leftSize=size; if(head.val==head.left.val-1){ leftSize++; max = Math.max(max, leftSize); }else{ leftSize=1; } nodeQueue.offer(head.left); sizeQueue.offer(leftSize); } if(head.right!=null){ int rightSize=size; if(head.val==head.right.val-1){ rightSize++; max = Math.max(max, rightSize); }else{ rightSize=1; } nodeQueue.offer(head.right); sizeQueue.offer(rightSize); } } return max; } |
http://algobox.org/binary-tree-longest-consecutive-sequence/
https://discuss.leetcode.com/topic/28269/two-simple-iterative-solutions-bfs-and-dfs
Every node is attached with a property “length” when pushed into the queue. It is the length of longest consecutive sequence end with that node. The answer is then the max of all popped lengths. The only difference of the two solutions is the data structure. BFS using
deque
and DFS using stack
.
from collections import deque
def longestConsecutive(self, root):
if not root:
return 0
ans, dq = 0, deque([[root, 1]])
while dq:
node, length = dq.popleft()
ans = max(ans, length)
for child in [node.left, node.right]:
if child:
l = length + 1 if child.val == node.val + 1 else 1
dq.append([child, l])
return ans
题目: find Longest Consective Increasing Sequence in Binary Tree from root
public class LICSinBinaryTree {
public int getLICSinBT(TreeNode root) {
if(root == null) {
return 0;
}
List<Integer> list = new ArrayList<Integer>();
list.add(Integer.MIN_VALUE);
helper(root, root.left, 1, list);
helper(root, root.right, 1, list);
return list.get(0);
}
public void helper(TreeNode pre, TreeNode cur, int num, List<Integer> list) {
if(cur == null || cur.val <= pre.val) {
if(num > list.get(0)) {
list.add(0, num);
}
return;
}
helper(cur, cur.left, num+1, list);
helper(cur, cur.right, num+1, list);
}
}
http://www.szeju.com/index.php/other/35241410.html
private int longest = 0; public int longestConsecutive(TreeNode root) { helper(root); return longest; } private int helper(TreeNode root) { if (root == null) { return 0; } int left = helper(root.left); int right = helper(root.right); int subtreeMax = 1; if (root.left != null && root.val + 1 == root.left.val) { subtreeMax = Math.max(left + 1, subtreeMax); } if (root.right != null && root.val + 1 == root.right.val) { subtreeMax = Math.max(right + 1, subtreeMax); } longest = Math.max(subtreeMax, longest); return subtreeMax; }
http://www.cnblogs.com/grandyang/p/5252599.html
下面这种写法是利用分治法的思想,对左右子节点分别处理,如果左子节点存在且节点值比其父节点值大1,则递归调用函数,如果节点值不是刚好大1,则递归调用重置了长度的函数,对于右子节点的处理情况和左子节点相同
int longestConsecutive(TreeNode* root) { if (!root) return 0; int res = 0; dfs(root, 1, res); return res; } void dfs(TreeNode *root, int len, int &res) { res = max(res, len); if (root->left) { if (root->left->val == root->val + 1) dfs(root->left, len + 1, res); else dfs(root->left, 1, res); } if (root->right) { if (root->right->val == root->val + 1) dfs(root->right, len + 1, res); else dfs(root->right, 1, res); } }X. Post-order traverse
https://github.com/YaokaiYang-assaultmaster/LeetCode/blob/master/LeetcodeAlgorithmQuestions/298.%20Binary%20Tree%20Longest%20Consecutive%20Sequence.md
The same with the above idea, we still need to check both left and right child of a parent node to get the result. The difference in the values of parent and child need to be 1, i.e. parent's value need to be less than child's value by 1.
This time we keep a global variable to make the process more intuitive, since the
result
is an int
and int
is a primitive type thus we cannot change it within another function.
We check the left and right subtree of a node, and record the length. There are 2 conditions:
- If
parent.val == child.val - 1
, then the current length should be the maximum one amongleft + 1
andright + 1
. - Otherwise, current length should be 1 since current node is the only one that is consecutive.
Then we update
result
correspondingly.
Time complexity:
O(n)
given there are n
nodes in the tree.
Space complexity:
O(n)
for the recursion stack. int result = 0;
public int longestConsecutive(TreeNode root) {
if (root == null) {
return 0;
}
getLongestConsecutive(root);
return result;
}
private int getLongestConsecutive(TreeNode root) {
int ret = 1;
if (root.left != null) {
int left = getLongestConsecutive(root.left);
if (root.val == root.left.val - 1) {
ret = Math.max(ret, 1 + left);
}
}
if (root.right != null) {
int right = getLongestConsecutive(root.right);
if (root.val == root.right.val - 1) {
ret = Math.max(ret, 1 + right);
}
}
result = Math.max(result, ret);
return ret;
}
用分治法遍历整个树。同时维护一个最长序列的变量longest。
遍历每个节点的时候,测试一下加上这个节点的最长序列是多少,决定是否要更新longest。
遍历完整棵树,longest就是我们求的值。
private int longest; /** * @param root the root of binary tree * @return the length of the longest consecutive sequence path */ public int longestConsecutive(TreeNode root) { longest = 0; helper(root); return longest; } private int helper(TreeNode root) { if (root == null) { return 0; } int left = helper(root.left); int right = helper(root.right); int subtreeLongest = 1; // at least we have root if (root.left != null && root.val + 1 == root.left.val) { subtreeLongest = Math.max(subtreeLongest, left + 1); } if (root.right != null && root.val + 1 == root.right.val) { subtreeLongest = Math.max(subtreeLongest, right + 1); } if (subtreeLongest > longest) { longest = subtreeLongest; } return subtreeLongest; }
public int longestConsecutive(TreeNode root) { return helper(root, null, 0); } private int helper(TreeNode root, TreeNode parent, int lengthWithoutRoot) { if (root == null) { return 0; } int length = (parent != null && parent.val + 1 == root.val) ? lengthWithoutRoot + 1 : 1; int left = helper(root.left, root, length); int right = helper(root.right, root, length); return Math.max(length, Math.max(left, right)); }
private class ResultType { int maxInSubtree; int maxFromRoot; public ResultType(int maxInSubtree, int maxFromRoot) { this.maxInSubtree = maxInSubtree; this.maxFromRoot = maxFromRoot; } } /** * @param root the root of binary tree * @return the length of the longest consecutive sequence path */ public int longestConsecutive(TreeNode root) { return helper(root).maxInSubtree; } private ResultType helper(TreeNode root) { if (root == null) { return new ResultType(0, 0); } ResultType left = helper(root.left); ResultType right = helper(root.right); // 1 is the root itself. ResultType result = new ResultType(0, 1); if (root.left != null && root.val + 1 == root.left.val) { result.maxFromRoot = Math.max( result.maxFromRoot, left.maxFromRoot + 1 ); } if (root.right != null && root.val + 1 == root.right.val) { result.maxFromRoot = Math.max( result.maxFromRoot, right.maxFromRoot + 1 ); } result.maxInSubtree = Math.max( result.maxFromRoot, Math.max(left.maxInSubtree, right.maxInSubtree) ); return result; }Follow up
http://www.1point3acres.com/bbs/thread-210141-1-1.html
一些空间放不下的follow up
Google Interview - Longest Continuous Path of Tree - 我的博客 - ITeye技术网站
给一个树root的pointer,树包含多个分支,树结构要自己创造。求一条最长路径。
例如(括号对应上面node)
树: 2
| | | |
5 7 3 6
(| | )( | )( | ) (| |)
6 3 2 4 5 8
|
3
返回3因为 (2-3-4) 这条线。优化要求时间O(n)
- static class NTreeNode {
- int val;
- List<NTreeNode> children = new ArrayList<>();
- }
- public int longestContinuousPath(NTreeNode root) {
- if(root == null) return 0;
- return longestContinuousPath(root, 1);
- }
- public int longestContinuousPath(NTreeNode root, int len) {
- int max = 0;
- for(NTreeNode child:root.children) {
- if(child == null) continue;
- int curLen = longestContinuousPath(child, child.val == root.val + 1 ? len + 1 : 1);
- max = Math.max(curLen, max);
- }
- return Math.max(max, len);
- }