博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
CareerCup Binary Tree the Maximum of 人
阅读量:4184 次
发布时间:2019-05-26

本文共 1668 字,大约阅读时间需要 5 分钟。

Given a binary tree, find 2 leaf nodes say X and Y such that F(X,Y) is maximum where F(X,Y) = sum of nodes in the path from root to X + sum of nodes in the path from root to Y - sum of nodes in the common path from root to first common ancestor of the Nodes X and Y

---------------------------------------------------------------------------------------------

My idea: 
1. Traverse the tree. For each node compute: 
R - the path from the root (i.e. the sum of all nodes from the root to this node) 
Q - the max path to a leaf 
This me be done recursively in O(N) space and time. 
2. Traverse the tree again maximizing Q of left subtree + Q of right subtree - R.

class TreeNode { public:  int val, toRoot, maxPath;  TreeNode *left, *right;  TreeNode(int val = 0):val(val), left(NULL), right(NULL) {}};class Solution { public:  int findMaxPath(TreeNode* root) {    if (root->left == NULL && root->right == NULL)      return root->val;        int l = INT_MIN, r = INT_MIN;    if (root->left) {      root->left->toRoot = root->toRoot + root->val;      root->left->maxPath = l = findMaxPath(root->left);    }    if (root->right) {      root->right->toRoot = root->toRoot + root->val;      root->right->maxPath = r = findMaxPath(root->right);        }    return root->val + max(l, r);  }  void findMaxSum(TreeNode* root) {    if (root == NULL)      return;    if (root->toRoot + root->maxPath < res)      res = root->toRoot + root->maxPath;    findMaxSum(root->left);    findMaxSum(root->right);   }  int findRes(TreeNode* root) {    int res = INT_MAX;    if (root == NULL)      return 0;    root->toRoot = 0;    root->maxPath = findMaxPath(root);    return findMaxSum(root);  }}

转载地址:http://bwboi.baihongyu.com/

你可能感兴趣的文章
Linux下安装pyenv
查看>>
virsh查询虚拟机列表
查看>>
右上三角矩阵的压缩(Python实现)
查看>>
Linux man 命令:查询命令使用手册
查看>>
CentOS配置静态ip
查看>>
Jinja2条件控制
查看>>
Linux /usr/src/kernels 缺失内核源码解决方案
查看>>
Git分支管理
查看>>
查看MySQL支持的字符集
查看>>
常见Linux目录
查看>>
在CLI中打印表格----gotable使用介绍
查看>>
Python str rjust方法
查看>>
CentOS7 安装MySQL
查看>>
Linux cd 命令 ----切换目录
查看>>
MySQL校对集
查看>>
左下三角矩阵压缩(Python)
查看>>
Go发送电子邮件
查看>>
Linux ls命令
查看>>
MySQL数据库操作
查看>>
Jinja2循环控制
查看>>