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

94.Binary Tree Inorder Traversal(非递归中序遍历)

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

标签:

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

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

   1

    \

    2

    /

   3

return [1,3,2].

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

confused what "{1,#,2,3}" means? > read moreon how binary tree is serialized on OJ.

HideTags

 Tree Hash Table 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> inorderTraversal(TreeNode *root) {
	vector<int> result;
	stack<TreeNode*> s;
	TreeNode* p = root;
	int flag = 0;//节点p的左孩子是否已经遍历的标志,flag=0应向左,flag=1应向右遍历
	while (p)
	{
			if (flag==0&&p->left)//有左且左未遍历,向左,自己压栈
			{
				s.push(p);
				p = p->left;
			}
			else//无左或左已经遍历,应向右
			{
				result.push_back(p->val);
				if (p->right)//有右,向右,flag可能为1,更新为0
				{
					p = p->right;
					flag = 0;
				}
				else if (!s.empty())//无右,s非空,pop
				{
					p = s.top();
					s.pop();
					flag = 1;//pop出来的,左孩子一定已遍历,下面往右
				}
				else
					return result;//s空,返回
			}
	}
	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 = inorderTraversal(t1);
	for (int i = 0; i < (int)result.size(); i++)
		cout << result[i] << " ";
	cout << endl;
	system("pause");

}


 

 

94.Binary Tree Inorder Traversal(非递归中序遍历)

标签:

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

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