Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Definition for a binary tree node.
- * public class TreeNode {
- * int val;
- * TreeNode left;
- * TreeNode right;
- * TreeNode(int x) { val = x; }
- * }
- */
- class Solution {
- public int longestConsecutive(TreeNode root) {
- if(root == null) return 0;
- helper(root);
- return re;
- }
- int helper(TreeNode root)
- {
- if(root == null) return 0;
- int left = helper(root.left), right = helper(root.right);
- int ans = 1; // for root
- if(root.left != null && root.left.val == root.val + 1)
- {
- ans += left;
- }
- if(root.right != null && root.right.val == root.val + 1)
- {
- ans = Math.max(ans, 1 + right);
- }
- re = Math.max(re, ans);
- return ans;
- }
- int re = 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement