树的测试框架:
1 // leetcodeTree.cpp : 定义控制台应用程序的入口点。 2 // 3 4 #include "stdafx.h" 5 #include <iostream> 6 #include <queue> 7 #include <stack> 8 #include <vector> 9 10 using namespace std; 11 12 struct TreeNode { 13 int val; 14 TreeNode *left; 15 TreeNode *right; 16 TreeNode(int x) : val(x), left(nullptr), right(nullptr) { }; 17 }; 18 struct TreeLinkNode { 19 int val; 20 TreeLinkNode *left; 21 TreeLinkNode *right; 22 TreeLinkNode *next; 23 TreeLinkNode(int x) : val(x) { left = nullptr; right = nullptr; next = nullptr; }; 24 }; 25 26 TreeNode* build(TreeNode *root, int val) { // 构造一棵树 27 if (root == nullptr) { 28 root = new TreeNode(val); 29 return root; 30 } 31 if (val < root->val) 32 root->left = build(root->left, val); 33 else 34 root->right = build(root->right, val); 35 36 return root; 37 } 38 39 vector<int> preOrderTraversal(TreeNode *root) { // 非递归先序遍历 40 vector<int> result; 41 stack<TreeNode*> stk; 42 if (root != nullptr) 43 stk.push(root); 44 while (!stk.empty()) { 45 TreeNode *p = stk.top(); 46 stk.pop(); 47 cout << '\t' << p->val; // 打印遍历序列 48 result.push_back(p->val); 49 50 if (p->right != nullptr) // 注意是先进栈右孩子,再进栈左孩子 51 stk.push(p->right); 52 if (p->left != nullptr) 53 stk.push(p->left); 54 } 55 return result; 56 } 57 58 int main() { 59 int t[] = {5,4,3,6,7}; 60 TreeNode* root = nullptr; 61 for(int i=0;i<sizeof(t)/sizeof(int);++i) // build a tree 62 build(root,t[i]); 63 64 preOrderTraversal(root); 65 66 return 0; 67 }