二叉树(先序遍历)非递归
生活随笔
收集整理的這篇文章主要介紹了
二叉树(先序遍历)非递归
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
為什么80%的碼農(nóng)都做不了架構(gòu)師?>>> ??
#include <iostream> #include <stack>struct Node {int data;struct Node *left;struct Node *right;Node(int x) {data = x;left = NULL;right = NULL;} };void PreOrder(struct Node *root) {if (root == NULL) return;std::stack<struct Node *> s;s.push(root);while(!s.empty()) {struct Node *tmp = s.top();printf("%d ", tmp->data);s.pop();if (tmp->right) s.push(tmp->right);if (tmp->left) s.push(tmp->left);} }void PreOrder2(struct Node *root) {if (root == NULL) return;std::stack<struct Node *>s;struct Node *tmp = root;while(tmp != NULL || !s.empty()) {while (tmp != NULL) {printf("%d ", tmp->data);s.push(tmp);tmp = tmp->left;}if (!s.empty()) {tmp = s.top();s.pop();tmp = tmp->right;}} }int main(int argc, char** argv) {Node *root = new Node(1);root->left = new Node(3);root->left->left = new Node(2);root->left->right = new Node(1);root->left->right->left = new Node(1);root->right = new Node(-1);root->right->left = new Node(4);root->right->left->left = new Node(1);root->right->left->right = new Node(2);root->right->right = new Node(5);root->right->right->right = new Node(2);PreOrder(root);printf("\n");PreOrder2(root);return 0; }?
輸出結(jié)果:
1 3 2 1 1 -1 4 1 2 5 2 1 3 2 1 1 -1 4 1 2 5 2?
轉(zhuǎn)載于:https://my.oschina.net/tsh/blog/862601
總結(jié)
以上是生活随笔為你收集整理的二叉树(先序遍历)非递归的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: qml demo分析(threadeda
- 下一篇: Veeam Backup Replic