問題:
5.1.1 Binary Tree Preorder Traversal
描述
Given a binary tree, return the preorder traversal of its nodes’ values.
For example: Given binary tree {1,#,2,3},
Note: Recursive solution is trivial, could you do it iteratively?
分析:用棧或者 Morris 遍歷。
實現:增添了一個makeTree()方法,生成需要的二叉樹。
#include<vector>
#include<iostream>
#include<stdlib.h>
#include<stack>
#include<vector>
#include<cmath>
// #include<iterator>
using namespace std;
static int count = 0;
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 *> stackTree;
TreeNode* p = root;
if(p != nullptr){
stackTree.push(root);
}
while(!stackTree.empty()){
p = stackTree.top();
stackTree.pop();
result.push_back(p->val);
if(p->right != nullptr) stackTree.push(p->right);
if(p->left != nullptr) stackTree.push(p->left);
}
return result;
}
int treeDeep(int n){
int i = 0;
if( n == 1){
return 2;
}else{
while(i < 20){
if(n > pow(2,i)-2 && n <= pow(2,i+1)-2){
return (i+1);
}
i++;
}
}
return 0;
}
void printTree(TreeNode *root){
cout<<root->val<<" ";
if(root->left != nullptr){
printTree(root->left);
}
if(root->right != nullptr){
printTree(root->right);
}
}
TreeNode* selectTree(TreeNode *root,int k){
cout<<root->val<<",";
if(root->left != nullptr){
count++;
cout<<"left:"<<count<<";"<<endl;
cout<<root->left->val<<",";
if(count == k){
return root->left;
}
}
if(root->right != nullptr){
count++;
cout<<"right:"<<count<<";"<<endl;
cout<<root->right->val<<",";
if(count == k){
return root->right;
}
}
selectTree(root->left,k - count);
selectTree(root->right,k - count);
}
void makeTree(TreeNode* root,int k){
TreeNode *tmpTree = new TreeNode(1);
sranddev();
tmpTree->val = rand()%100;
if(count < k && root->left == nullptr){
root->left = tmpTree;
count++;
}else if(count < k && root->right == nullptr){
root->right = tmpTree;
count++;
}
if(count < k){
makeTree(root->left,k);
makeTree(root->right,k);
}
}
int main(){
TreeNode *root = new TreeNode(10);
int size;
size = 10;
TreeNode *root1,*root2;
root1 = root2;
// for(int i = 1; i < 10;++i){
// int deep = treeDeep(i);
// cout<<"i="<<i<<"deep="<<deep<<endl;
// TreeNode *tmpTree = new TreeNode(1);
// sranddev();
// tmpTree->val = rand()%100;
// if(i % 2 == 1){
// root1 = root;
// for(int j = 0; j < deep-1 &&(!root1);j++){
// root1 = root1->left;
// }
// root1->left = tmpTree;
// }else{
// root2 = root;
// for(int j = 0; j < deep-1 && (!root2);j++){
// root2 = root2->right;
// }
// root2->right = tmpTree;
// }
// }
makeTree(root,10);
printTree(root);
cout<<endl;
// selectTree(root,2);
// cout<<endl;
vector<int> res;
res = preorderTraversal(root);
for(vector<int>::iterator it = res.begin(); it != res.end();it++){
cout<<*it<<" ";
}
cout<<endl;
}