LeetCode 298 - Binary Tree Longest Consecutive Sequence


LeetCode 549 - Binary Tree Longest Consecutive Sequence II
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
        \
         5
Longest consecutive sequence path is 3-4-5, so return 3.
   2
    \
     3
    / 
   2    
  / 
 1
Longest consecutive sequence path is 2-3,not3-2-1, so return 2.
X. PreOrder Java
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)
                        )
                       );
    }

https://discuss.leetcode.com/topic/29205/simple-recursive-dfs-without-global-variable
    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 Search
http://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.html
12     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 TreeBinary 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)));  
    }
X. BFS
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
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,则递归调用重置了长度的函数,对于右子节点的处理情况和左子节点相同

    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:
  1. If parent.val == child.val - 1, then the current length should be the maximum one among left + 1 and right + 1.
  2. 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;
    }
https://xuezhashuati.blogspot.com/2017/03/lintcode-595-binary-tree-longest.html
用分治法遍历整个树。同时维护一个最长序列的变量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)

  1. static class NTreeNode {  
  2.     int val;  
  3.     List<NTreeNode> children = new ArrayList<>();  
  4. }  
  5.   
  6. public int longestContinuousPath(NTreeNode root) {  
  7.     if(root == nullreturn 0;  
  8.     return longestContinuousPath(root, 1);  
  9. }  
  10.   
  11. public int longestContinuousPath(NTreeNode root, int len) {  
  12.     int max = 0;  
  13.     for(NTreeNode child:root.children) {  
  14.         if(child == nullcontinue;  
  15.         int curLen = longestContinuousPath(child, child.val == root.val + 1 ? len + 1 : 1);  
  16.         max = Math.max(curLen, max);  
  17.     }  
  18.     return Math.max(max, len);  
  19. }

Labels

LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

Popular Posts