leetcode:二叉树之Binary Tree Preorder Traversal
题目:
Given a binary tree, return the preorder traversal of its nodes’ values.
For example,
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,2,3].
Note: Recursive solution is trivial, could you do it iteratively?
即:二叉树前序遍历
C++实现:
#include <iostream>
#include <vector>
#include <malloc.h>
#include <stack>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) { }
};
void CreateBiTree(TreeNode* &T)
{
char ch;
cin>>ch;
if(ch=='#')
T=NULL;
else
{
T = (TreeNode*)malloc(sizeof(TreeNode));
if(!T) exit(0);
T->val = ch-'0';
CreateBiTree(T->left);
CreateBiTree(T->right);
}
}
//使用栈
vector<int> preorderTraversal(TreeNode *root)
{
vector<int> result;
const TreeNode *p;
stack<const TreeNode *> s;
p = root;
if (p != NULL)
s.push(p);
while (!s.empty())
{
p = s.top();
s.pop();
result.push_back(p->val);
if (p->right != NULL)
s.push(p->right);
if (p->left != NULL)
s.push(p->left);
}
return result;
}
int main()
{
TreeNode* root(0);
CreateBiTree(root);
cout<<"输出前序遍历结果:"<<endl;
vector<int> v;
v=preorderTraversal(root);
for(int i = 0;i < v.size();i++)
cout<<v[i];
cout<<endl;
return 0;
}
测试结果: