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

Binary Tree Inorder Traversal

时间:2015-02-06 13:12:19      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:

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

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

   1
         2
    /
   3

return [1,3,2].

解题思路:简单的中序非递归遍历,用栈实现;

#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>ResultVectorPsotorder;
	stack<TreeNode*>StackNode;
	if (root == NULL)
		return ResultVectorPsotorder;
	TreeNode*CurNode = root;
	while (1){
		while (CurNode!=NULL){
			StackNode.push(CurNode);
			CurNode = CurNode->left;
		}
		if (StackNode.empty())
			break;
		CurNode = StackNode.top();
		ResultVectorPsotorder.push_back(CurNode->val);
		StackNode.pop();
		CurNode = CurNode->right;
	}
	return ResultVectorPsotorder;
}



Binary Tree Inorder Traversal

标签:

原文地址:http://blog.csdn.net/li_chihang/article/details/43562939

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