Advertisement
lifeiteng

298. Binary Tree Longest Consecutive Sequence

Sep 12th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.84 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * public class TreeNode {
  4.  *     int val;
  5.  *     TreeNode left;
  6.  *     TreeNode right;
  7.  *     TreeNode(int x) { val = x; }
  8.  * }
  9.  */
  10. class Solution {
  11.     public int longestConsecutive(TreeNode root) {
  12.         if(root == null) return 0;
  13.         helper(root);
  14.         return re;
  15.     }
  16.    
  17.     int helper(TreeNode root)
  18.     {
  19.         if(root == null) return 0;
  20.         int left = helper(root.left), right = helper(root.right);
  21.         int ans = 1; // for root
  22.         if(root.left != null && root.left.val == root.val + 1)
  23.         {
  24.             ans += left;
  25.         }
  26.         if(root.right != null && root.right.val == root.val + 1)
  27.         {
  28.             ans = Math.max(ans, 1 + right);
  29.         }
  30.         re = Math.max(re, ans);
  31.         return ans;
  32.     }
  33.    
  34.     int re = 0;
  35.    
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement