LeetCode 298. Binary Tree Longest Consecutive Sequence

Problem Description:

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).

Example 1:

Input:

   1
    \
     3
    / \
   2   4
        \
         5

Output: 3

Explanation: Longest consecutive sequence path is 3-4-5, so return 3.

Example 2:

Input:

   2
    \
     3
    / 
   2    
  / 
 1

Output: 2 

Explanation: Longest consecutive sequence path is 2-3, not 3-2-1, so return 2.
 题解:
这个题还蛮有意思的,考察的知识点稍多。
看到这个题首先想到的是用bfs,把空的节点也放入队列,每行的长度取改行首尾非空节点的距离,但是这样会处理不少空节点,空间和时间效率都不好。
然后想到的是dfs的做法,像堆一样构建每行树节点的子节点。当前节点的index为i,则其左子节点的index为2*i+0,右子节点的index为2*i+1.
            0
          /   \
         0     1
        /\    /\
       0  1  2  3
代码如下
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int res;
    public int widthOfBinaryTree(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        res = 1;
        dfs(list, root, 0, 0);
        // System.out.println(list.size());
        return res;
    }
    
    private void dfs(List<Integer> list, TreeNode root, int depth, int index) {
        if(root == null) return;
        if(list.size() <= depth) {
            list.add(index);
        } else {
            res = Math.max(res, index - list.get(depth) + 1);
        }
        dfs(list, root.left, depth + 1, index + index);
        dfs(list, root.right, depth + 1, index + index + 1);
        
    }
    
}

 

 
 
posted @ 2019-06-05 21:39  起点菜鸟  阅读(195)  评论(0编辑  收藏  举报