非递归和递归方法遍历二叉树

来源:互联网 发布:掌酷主题软件 编辑:程序博客网 时间:2024/05/19 17:24
</pre><p><pre class="cpp" name="code">struct node { int value; struct node * left; struct node * right;};void preOrderBTree(struct node * head) {if (head == NULL)return;stack<struct node *> s;s.push(head);while (!s.empty()) {struct node * tmp = s.top();cout << tmp->value << " ";s.pop();if (tmp->right != NULL)s.push(tmp->right);if (tmp->left != NULL)s.push(tmp->left);}cout << endl;}
<pre class="cpp" name="code">void circuseBTreePreOrder(struct node * head) {if (head == NULL)return;cout << head->value << " ";circuseBTreePreOrder(head->left);circuseBTreePreOrder(head->right);}
void anotherPreOrder(struct node * head) {if (head == NULL)return;stack<struct node *> s;s.push(head);cout << head->value << " ";struct node * tmp = head->left;while (1) {while (tmp != NULL) {s.push(tmp);cout << tmp->value << " ";tmp = tmp->left;}if (s.empty())break;tmp = s.top()->right;s.pop();}}


非递归中序遍历二叉树:

void midOrder(struct node * head) {if (head == NULL)return;struct node * tmp = head->left;stack<struct node *> s;s.push(head);while (1) {while (tmp != NULL) {s.push(tmp);tmp = tmp->left;}if (s.empty())break;tmp = s.top()->right;cout << s.top()->value << " ";s.pop();}}

层次遍历二叉树:

void layerOrder(struct node * head) {if (head == NULL)return;queue<struct node *> q;;q.push(head);while (!q.empty()) {struct node * cur = q.front();q.pop();cout << cur->value << " ";if (cur->left != NULL) {q.push(cur->left);}if (cur->right != NULL) {q.push(cur->right);}}}


非递归后序遍历二叉树:

void postOrder(struct node * head) {if (head == NULL)return;stack<struct node *> s;struct node * r = NULL;s.push(head);struct node * tmp = head->left;int flag = 0;while (!s.empty()) {while (tmp != NULL) {s.push(tmp);tmp = tmp->left;}if (s.top() == head) {flag++;}if (flag == 2) {cout << s.top()->value << " ";break;}if ((s.top()->right == NULL) || (s.top() == r)) {cout << s.top()->value << " ";s.pop();tmp = NULL;}else {tmp = s.top()->right;r = s.top();}}}

时间复杂度: O(n)

递归的中序遍历和后序遍历方法与文中的前序遍历方法相同,不同的地方就是打印输出的位置。




0 0
原创粉丝点击