Binary Tree Longest Consecutive Sequence

来源:互联网 发布:mac照片复制到移动硬盘 编辑:程序博客网 时间:2024/05/06 03:37

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

For example,

   1    \     3    / \   2   4        \         5
Longest consecutive sequence path is 3-4-5, so return 3.
   2    \     3    /    2      /  1

Longest consecutive sequence path is 2-3,not3-2-1, so return 2.

思路:求最大值,就必须有个变量keep住最大,然后递归需要传递的是父亲的节点,然后想到的是preorder,先访问当前,然后左右。注意consecutive,父与子的关系是+1.

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int longestConsecutive(TreeNode root) {        if(root == null) return 0;        int[] res = new int[]{0};        TreeNode pre = null;        find(root, res, 1, pre);        return res[0];    }        public void find(TreeNode root, int[] res, int count, TreeNode pre) {        if(root == null) return;        if(pre!=null){            if(root.val == pre.val+1){                count++;            } else {                count = 1;            }        }        pre = root;        res[0] = Math.max(res[0], count);        find(root.left, res, count, pre);        find(root.right, res, count, pre);    }}



0 0
原创粉丝点击