298.Binary-Tree-Longest-Consecutive-Sequence

298. Binary Tree Longest Consecutive Sequence

题目地址

https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/

题目描述

Given a binary tree, find the length of the longest consecutive sequence path.

The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The longest consecutive path need to be from parent to child (cannot be the reverse).

代码

Approach #1 Top Down DFS

Time: O(N) && Space: O(N)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
  public int longestConsecutive(TreeNode root) {
        return dfs(root, null, 0);
  }

  private int dfs(TreeNode p, TreeNode parent, int length) {
    if (p == null)        return length;
    if (parent != null && p.val == parent.val + 1) {
      length = length + 1;
    } else {
      length = 1;
    }

    return Math.max(length, 
                   Math.max(dfs(p.left, p, length),
                           dfs(p.right, p, length)));
  }
}

Approach #2 Bottom Up DFS

class Solution {
  private int maxLength = 0;
  public int longestConsecutive(TreeNode root) {
    dfs(root);
    return maxLength;
  }

  private int dfs(TreeNode p) {
    if (p == null)        return 0;
    int L = dfs(p.left) + 1;
    int R = dfs(p.right) + 1;
    if (p.left != null && p.val + 1 != p.left.val) {
      L = 1;
    }
    if (p.right != null && p.val + 1 != p.right.val) {
      R = 1;
    }
    int length = Math.max(L, R);
    maxLength = Math.max(maxLength, length);
    return length;
  }
}

Last updated