码迷,mamicode.com
首页 > 其他好文 > 详细

144.Binary Tree Preorder Traversal(非递归前序遍历)

时间:2015-01-30 22:53:36      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:

Given a binary tree, return the preorder traversal of itsnodes‘ values.

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

   1

    \

    2

    /

   3

return [1,2,3].

Note: Recursive solution istrivial, could you do it iteratively?

HideTags

 Tree Stack 


#pragma once
#include<iostream>
#include<vector>
#include<stack>
using namespace std;

struct TreeNode {
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};


vector<int> preorderTraversal(TreeNode *root) {
	vector<int> result;
	stack<TreeNode*> s;
	TreeNode* p = root;
	while (p)
	{
		result.push_back(p->val);
		if (p->left)//有左,向左,右压栈
		{
			if (p->right)
				s.push(p->right);
			p = p->left;
		}
		else if (p->right)//无左,有右,向右
			p = p->right;
		else if (!s.empty())//无左无右,栈不空,pop
		{
			p = s.top();
			s.pop();
		}
		else
			return result;//无左无右栈空,返回
	}
	return result;//不可少,若root==NULL,用这一句返回
}

void main()
{
	TreeNode* t1 = new TreeNode(1);
	TreeNode* t2 = new TreeNode(2);
	TreeNode* t3 = new TreeNode(3);
	TreeNode* t4 = new TreeNode(4);
	TreeNode* t5 = new TreeNode(5);
	TreeNode* t6 = new TreeNode(6);
	TreeNode* t7 = new TreeNode(7);
	TreeNode* t8 = new TreeNode(8);
	TreeNode* t9 = new TreeNode(9);

	TreeNode* t0 = new TreeNode(0);
	TreeNode* t10 = NULL;

	t1->right = t2;
	t2->left = t3;

	t4->left = t5;
	t4->right = t6;

	t7->right = t8;
	t8->right = t9;


	t1->left = t7;
	t7->left = t4;

	vector<int>result = preorderTraversal(t1);
	for (int i = 0; i < (int)result.size(); i++)
		cout << result[i] << " ";
	cout << endl;
	system("pause");

}


144.Binary Tree Preorder Traversal(非递归前序遍历)

标签:

原文地址:http://blog.csdn.net/hgqqtql/article/details/43308211

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!