简体   繁体   中英

find the maximum path sum.,which we can start and end in any node in the binary tree

here is the problem link https://leetcode.com/problems/binary-tree-maximum-path-sum/ , and my solution is i can transform from a tree to a array,so i adopt to use preorder tree walk,and i refer kadane's algorithm to find max value in the array,here is my code,when i run the program ,the result always be zero,but in my opnion,it is should be right, i cant figure out why it doesn't work,and by the way ,the problem hint is using dfs,i am not familiar with dfs,can anyone provide some thought in this problem by using dfs method,and tell me how to study dfs well,any papers or notes,videos is ok,thanks in advance!

 int maxPathSum(TreeNode *root) {
  vector<int>res;
  int max;
  if (root){
      res.push_back(root->val);
      maxPathSum(root->left);
      maxPathSum(root->right);
  }
  else{
      return 0;
  }
  max = maxpathsum1(res);
  return max;
}
int maxpathsum1(vector<int>&res){
    int cur,max;
    int len = res.size();
    cur = 0;
    max = 0;
    for (int i=0;i<len-1;i++){
        cur = cur+res[i];
        if (cur<0){
            cur = 0;
        }
        if (max<cur){
            max = cur;
        }
    }
    return max;
}

A dfs is an algorithm for traversing over all nodes in a tree (more generally in a graph), so it can indeed fit to your problem. You can just ran the dfs algorithm, while summing the max path each time between the left sub-tree and the right one + the root node itself. You can find much more on dfs in Coreman's "Introduction to Algorithms" book.

Regarding yours (very similar) solution, you are not using the return value of the recursion in the "maxPathSum" function. You should take this values returned after calling the recursion on "root->left" and "root->right", validate they are positive and sum them into some "max2" variable and use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM