124. Binary Tree Maximum Path Sum&145.Binary Tree Postorder Traversal

题目: Given a binary tree, find the maximum path sum.

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;
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值