二叉樹最長連續序列 - LintCode

描述
給一棵二叉樹,找到最長連續路徑的長度。
這條路徑是指 任何的節點序列中的起始節點到樹中的任一節點都必須遵循 父-子 聯繫。最長的連續路徑必須是從父親節點到孩子節點(不能逆序)。

樣例
舉個例子:

   1
    \
     3
    / \
   2   4
        \
         5

最長的連續路徑爲 3-4-5,所以返回 3。

   2
    \
     3
    / 
   2    
  / 
 1

最長的連續路徑爲 2-3 ,而不是 3-2-1 ,所以返回 2。

思路

#ifndef C595_H
#define C595_H
#include<iostream>
#include<map>
using namespace std;
class TreeNode{
public:
    int val;
    TreeNode *left, *right;
    TreeNode(int val){
        this->val = val;
        this->right = this->left = NULL;
    }
};
class Solution {
public:
    /**
    * @param root: the root of binary tree
    * @return: the length of the longest consecutive sequence path
    */
    int longestConsecutive(TreeNode * root) {
        // write your code here
        if (!root)
            return 0;
        m[root] = 1;
        helper(root);
        int max = 0;
        for (auto c : m)
        {
            if (c.second > max)
                max = c.second;
        }
        return max;
    }
    //從根節點開始處理,存放根節點及其連續序列長度,分別處理左右結點
    //如果結點子樹的值爲結點的值+1,則其連續序列長度爲結點連續序列長度+1
    void helper(TreeNode *root)
    {
        if (!root)
            return;
        if (root->left)
        {
            if (root->left->val == root->val + 1)
            {
                m[root->left] = m[root] + 1;
            }
            else
                m[root->left] = 1;
            helper(root->left);
        }
        if (root->right)
        {
            if (root->right->val == root->val + 1)
            {
                m[root->right] = m[root] + 1;
            }
            else
                m[root->right] = 1;
            helper(root->right);
        }
    }
    map<TreeNode*, int> m;//存放結點及其連續序列的長度
};
#endif
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章