Leetcode - Binary Tree Longest Consecutive Sequence

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 则是实现的一种具体的实际的方式。
就我所知,
有些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

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/7a6ed4f20eb1#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞