For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
给定一个二叉树,找出最大路径和。该路径可以从二叉树任何结点开始,也可以到任何结点结束。
思路:想要路径和最大,路径经过的节点数量应该越多越好。路径必须会经过某个根节点,就会经过根节点的左孩子和右孩子。路径和等于左孩子到叶节点的某条路径和加上根节点再加上右孩子到叶节点的某条路径。所以要求最大的路径和就是lmax(左孩子路径最大值)+root+rmax(右孩子路径最大值)。除了根节点以外,其他节点的最大路径和就是root+max(lmax,rmax)。
class Solution {
public:
int maxSum;
int maxPathSum(TreeNode* root)
{
if (root == NULL)
return 0;
maxSum = root->val;
getPathSum(root);
return maxSum;
}
int getPathSum(TreeNode* root)
{
if (root == NULL)
return 0;
int lmax, rmax;
lmax = max(0, getPathSum(root->left));
rmax = max(0, getPathSum(root->right));
int val = root->val;
int sum = val + lmax + rmax;//求以当前根节点为中心的最大路径和
maxSum = max(maxSum, sum);
return val + max(lmax, rmax);//返回当前根节点的一条最大路径
}
};
题目: Given a binary tree, return the postorder traversal of its nodes' values.Note: Recursive solution is trivial, could you do it iteratively?
给定一个二叉树,返回后序遍历。注意:不使用递归。
思路:后序遍历二叉树是先输出子节点再输出父节点,与给出的输入序列是相反的顺序。这种先入后出的顺序用一个栈来模拟最适合了。按照输入序列的顺序先序遍历二叉树,将遍历到的根节点压入栈内。直到遍历到叶节点的时候弹出,并且输出结果,回溯的时候,用一个数据结构记录上一步弹出的节点,如果当前的节点是上一步节点的父节点,那么这个节点也应该弹出,并且输出结果。直到栈为空,结果就输出完毕。
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> nodes;
if (root == NULL)
return res;
nodes.push(root);
TreeNode* child = root;
while (!nodes.empty())
{
TreeNode* cur = nodes.top();
if ((cur->left == NULL && cur->right == NULL) || cur->left == child || cur->right == child)
{
nodes.pop();
res.push_back(cur->val);
child = cur;
}
else
{
if (cur->right)
nodes.push(cur->right);
if (cur->left)
nodes.push(cur->left);
}
}
return res;
}
};