298. Binary Tree Longest Consecutive Sequence

最后更新

三刷。
11-Jan-2017

简单的二叉树,没啥技巧可言,DFS..

Time: O(n)
Space: O(depth)

public class Solution {
    int max = 0;
    public int longestConsecutive(TreeNode root) {
        if (root == null) return max;
        
        dfs(root, 0);
        return max;
    }
    
    public void dfs(TreeNode root, int depth) {
        max = Math.max(max, ++ depth);
        if (root == null) return;
        if (root.left == null && root.right == null) return;
        
        if (root.left != null) {
            if (root.val + 1 == root.left.val) {
                dfs(root.left, depth);
            } else {
                dfs(root.left, 0);
            }
        }
        
        if (root.right != null) {
            if (root.val + 1 == root.right.val) {
                dfs(root.right, depth);
            } else {
                dfs(root.right, 0);
            }
        }
    }
}

好像就是楞做,记录长度就行了。
判断失败就从0开始。。

public class Solution 
{
    int max = 0;
    public int longestConsecutive(TreeNode root) 
    {
        if(root == null) return 0;

        helper(root,0);
        return max;
    }
    
    public void helper(TreeNode root, int c)
    {
        max = Math.max(max,c+1);
        if(root.left == null && root.right == null) return;
        if(root.left != null)
        {
            if(root.val+1 == root.left.val) helper(root.left,c+1);
            else helper(root.left,0);
            
        }
        
        if(root.right != null)
        {
            if(root.val+1 == root.right.val) helper(root.right,c+1);
            else helper(root.right,0);
            
        }
    }
}

iterative比较难啊。。貌似得记录每一个NODE的当时情况,就得有个MAP之类的了。。

先不考虑了 二刷 再说……



二刷。

DFS,不连续了就更新一下。

二刷做的不如一刷好,写得不如一刷简洁。

public class Solution {
    int res;
    public int longestConsecutive(TreeNode root) {
        if (root == null) return 0;
        this.res = 1;
        twoShots(root.left, root.val, 1);
        twoShots(root.right, root.val, 1);
        return res;
    }
    
    public void twoShots(TreeNode root, int prev, int num) {
        res = Math.max(res, num);
        if (root == null) return;
        if (root.val == prev + 1) {
            twoShots(root.left, prev + 1, num + 1);
            twoShots(root.right, prev + 1, num + 1);
        } else {
            twoShots(root.left, root.val, 1);
            twoShots(root.right, root.val, 1);
        }
    }
}
原文地址:https://www.cnblogs.com/reboot329/p/5958951.html