首页 > 其他 > 详细

leetcode - Binary Tree Postorder Traversal

时间:2016-01-03 22:24:54      阅读:230      评论:0      收藏:0      [点我收藏+]

Given a binary tree, return the postorder traversal of its nodes‘ values.

For example:
Given binary tree {1,#,2,3},

   1
         2
    /
   3

return [3,2,1].

Note: Recursive solution is trivial, could you do it iteratively?

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

//BinTree的后序遍历
struct TreeNode
{
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) : val(x),left(NULL),right(NULL) {}
};
class Solution {
public:
	std::vector<int> postorderTraversal(TreeNode *root) {
		std::vector<int> vec;
		BinTree(root,vec);
		return vec;
    }
	void BinTree(TreeNode *root,std::vector<int> &vec)
	{
		if(root != NULL)
		{
			BinTree(root->left,vec);
			BinTree(root->right,vec);
			vec.push_back(root->val);
		}
	}
private:
	std::vector<int> vec;
};


leetcode - Binary Tree Postorder Traversal

原文:http://www.cnblogs.com/mengfanrong/p/5097225.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!