My code:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private int max = Integer.MIN_VALUE;
public int longestConsecutive(TreeNode root) {
if (root == null) {
return 0;
}
helper(root, root.val - 1, 0);
return max;
}
private void helper(TreeNode root, int parent, int number) {
if (root == null) {
max = Math.max(max, number);
return;
}
if (root.val == parent + 1) {
max = Math.max(max, number + 1);
helper(root.left, root.val, number + 1);
helper(root.right, root.val, number + 1);
}
else {
max = Math.max(max, 1);
helper(root.left, root.val, 1);
helper(root.right, root.val, 1);
}
}
}
自己寫了出來辫塌,dfs recursion top-down
沒什么難的。
然后還有一種bottom up的思想浩姥,其實差不多蘸吓。
https://leetcode.com/articles/binary-tree-longest-consecutive-sequence/
dfs, bfs 都是一種思想,
recursion, iteration 則是實現(xiàn)的一種具體的實際的方式例驹。
就我所知岂丘,
有些dfs,既可以recursion的寫眠饮,也可以iteration的寫
有些bfs奥帘,既可以iteration的寫,也可以recursion的寫
Anyway, Good luck, Richardo! -- 09/08/2016
My code:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private int max = Integer.MIN_VALUE;
public int longestConsecutive(TreeNode root) {
if (root == null) {
return 0;
}
helper(root, null, 0);
return max;
}
private void helper(TreeNode root, TreeNode parent, int length) {
if (root == null) {
return;
}
length = (parent != null && root.val == parent.val + 1 ? length + 1 : 1);
max = Math.max(max, length);
helper(root.left, root, length);
helper(root.right, root, length);
}
}
reference:
https://leetcode.com/articles/binary-tree-longest-consecutive-sequence/
Anyway, Good luck, Richardo! -- 09/28/2016