Skip to content

Latest commit

 

History

History
41 lines (29 loc) · 1.04 KB

298.md

File metadata and controls

41 lines (29 loc) · 1.04 KB

Solution 1

后序遍历, 遍历过程中返回从该节点开始的result, 并更新全局的maxResult.

class Solution {
    public int longestConsecutive(TreeNode root) {
        maxResult = 0;

        longestConsecutiveStartWith(root);

        return maxResult;
    }

    private int maxResult = 0;

    private int longestConsecutiveStartWith(TreeNode node) {
        if (node == null) {
            return 0;
        }

        int result = 1;

        int leftResult = longestConsecutiveStartWith(node.left);
        int rightResult = longestConsecutiveStartWith(node.right);

        if (node.left != null && node.left.val == node.val + 1) {
            result = Math.max(result, leftResult + 1);
        }
        if (node.right != null && node.right.val == node.val + 1) {
            result = Math.max(result, rightResult + 1);
        }

        maxResult = Math.max(maxResult, result);

        return result;
    }
}