c_cpp [tree] [path]二叉树中的最大和路径。返回路径。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp [tree] [path]二叉树中的最大和路径。返回路径。相关的知识,希望对你有一定的参考价值。

#include <iostream>
#include <vector>
#include <string>
#include <climits>
using namespace std;

struct treenode {
    int val;
    treenode *left, *right;
    treenode(int v) : val(v), left(NULL), right(NULL) {}
};
// ==========================================================================
// method 1, TOP-DOWN, first, find the leaf; then, get the path
// spent long time to make below function correct
// path has root-to-leaf nodes

// 1st step: get the leaf that has max_sum
void max_sum_path(treenode *r, int curr_sum, int& max_sum, treenode* &leaf) {
    if(!r) return;
    curr_sum += r->val;
    if(!r->left && !r->right) {
        if(max_sum < curr_sum) {
            max_sum = curr_sum;
            leaf = r;
        }
    }
    max_sum_path(r->left, curr_sum, max_sum, leaf);
    max_sum_path(r->right, curr_sum, max_sum, leaf);
}

// 2nd step: according to the obtained leaf, get the path
bool check_and_get_path(treenode *r, treenode *leaf, vector<treenode*> &path) {
    if(!r) return false;
    if(r == leaf) {
        path.push_back(r);
        return true;
    }
    path.push_back(r);
    if(check_and_get_path(r->left, leaf, path) || check_and_get_path(r->right, leaf, path))
        return true;

    path.pop_back();
    return false;
}


// ================== best version! easy to understand ==============================
// method 2, BOTTOM-UP. path has leaf-to-root value
int max_path_sum4(treenode *r, vector<int> &path) {
    if(!r) return 0;
    vector<int> p1, p2;
    int s1 = max_path_sum4(r->left, p1);
    int s2 = max_path_sum4(r->right, p2);
    int sum;
    if(s1 > s2) {
        sum = r->val + s1;
        path = p1;
    } else {
        sum = r->val + s2;
        path = p2;
    }
    path.push_back(r->val);
    return sum;
}



// if just obtain the max sum, not the path, it's easy
int max_path_sum(treenode *r) {
    if(!r) return 0;
    if(!r->left && !r->right) return r->val;
    return r->val + max(max_path_sum(r->left), max_path_sum(r->right));
}


int main()
{
    vector<treenode*> path;
   int max_sum = INT_MIN;
   treenode *r = new treenode(3);
   r->left = new treenode(2); 
   r->right = new treenode(9);
   r->left->left = new treenode(1);
   treenode *leaf = NULL;
   
   max_sum_path(r, 0, max_sum, leaf);
   check_and_get_path(r, leaf, path);
   
   for(auto n : path) cout << n->val << " ";
   
   cout << endl;
   
   vector<int> path2;
   max_path_sum4(r, path2);
   for(int d : path2) {
       cout << d << " ";
   }
}

以上是关于c_cpp [tree] [path]二叉树中的最大和路径。返回路径。的主要内容,如果未能解决你的问题,请参考以下文章

124. 二叉树中的最大路径和(Binary Tree Maximum Path Sum)

二叉树中的最大路径和 · Binary Tree Maximum Path Sum

124. 二叉树中的最大路径和

二叉树中的最大和路径

1457. 二叉树中的伪回文路径

1457. 二叉树中的伪回文路径