二叉树最长路径

问题描述

二叉树最长路径_第1张图片

思路和代码

先参考最长子序列求解方法,先序遍历的时候,我们把当前遍历的分支作为一个序列,然后利用最长序列的方式求解。递归过程中,保留树的高度,用高度差作为长度。注意递归结束时,需要从哈希表中移除当前节点的值。

#include 
#include 
#include 
#include 

const int TAG = -100;

struct Node {
    int val;
    std::shared_ptr<Node> left{nullptr}, right{nullptr};
    Node(int n = 0): val(n), left(nullptr), right(nullptr) {}
};

std::unordered_map<int, int> ump;  // 存储 累积和 与 高度
int num;     // 规定数字
int maxLen;  // 当前最长路径长度

std::shared_ptr<Node> CreateTreeNode() {
    int n;
    std::cin >> n;
    if (n == TAG) {
        return nullptr;
    }
    auto root = std::make_shared<Node>(n);
    root->left = CreateTreeNode();
    root->right = CreateTreeNode();
    return root;
}

void MaxLenPath(const std::shared_ptr<Node>& root, int h, int preSum) {
    if (root == nullptr) {
        return;
    }
    int sum = preSum + root->val;  // 当前分支作为一个序列
    int k = sum - num;
    auto it = ump.find(k);
    if (it == ump.end()) {
        ump.emplace(std::make_pair(k, h));
    } else {
        int len = h - it->second;
        if (len > maxLen) {
            maxLen = len;
        }
    }
    MaxLenPath(root->left, h + 1, sum);
    MaxLenPath(root->right, h + 1, sum);
    ump.erase(k);  // 删除对应元素,因为已经停止这个分支了
}

inline void Print(const std::vector<std::shared_ptr<Node>>& vec) {
    for (const auto &p: vec) {
        std::cout << p->val << " ";
    }
    std::cout << std::endl;
}

int main() {
    // -3 3 1 -100 -100 0 1 -100 -100 6 -100 -100 -9 2 -100 -100 1 -100 -100
    ump.emplace(std::make_pair(0, -1));  // 初始化的数据,处理根节点
    maxLen = -1;
    std::cout << "Create Tree:\n";
    auto root = CreateTreeNode();
    std::cout << "input num: ";
    std::cin >> num;
    MaxLenPath(root, 0, 0);
    std::cout << "maxLen = " << maxLen << std::endl;
    return 0;
}

参考

  • https://blog.csdn.net/qq_35976351/article/details/103864846

你可能感兴趣的:(算法与数据结构,二叉树,二叉树最长路径,最长子序列,算法)