Implement non-recursive traversal of a binary tree (2) - Study Notes

Implement non-recursive traversal of a binary tree (2) - Study Notes

Foreword

I found a very practical and simple algorithm on Leetcode, share with you.
The advantage of this algorithm is that in general recursive traversal, simply adjust the order of the code, can be easily implemented before, during and after preorder.

Thinking

Algorithms ideas are as follows:

  1. First create a stack.
  2. For each node in the stack, we give it a label, false on behalf of non-traverse, to true representative has traversed.
  3. When the pull tag is encountered false node, the left and right nodes respectively labeled false insert stack is labeled as node itself to true .
  4. Flag is encountered the stack true node directly outputs.
  5. The above operation is repeated until the stack is empty.

Code

void Fun(Tree **root) {
	if (*root != NULL) {
	    // 堆栈
		stack<Tree*> s;
		//标签
		stack<bool> tab;
        
        //插入头指针,标签为false
		s.push(*root);
		tab.push(false);

		while (s.size() > 0) {
		    //弹出指针和标签
			Tree *p = s.top();
			bool c = tab.top();
			s.pop();
			tab.pop();

            //指针为空,continue
			if (p == NULL)
				continue;
            
            //标签为true,输出当前节点的值
            //标签为false,将左右节点标记为false插入,节点本身标记为true插入
			if (c) {
				cout << p->val << " ";
			}
			else {
			    //前序遍历
				s.push(p->right);
				tab.push(false);
				
				s.push(p->left);
				tab.push(false);
				
				s.push(p);
				tab.push(true);
                //------------------//
                //中序遍历
                //s.push(p->right);
				//q.push(false);

				//s.push(p);
				//q.push(true);

				//s.push(p->left);
				//q.push(false);
                //------------------//
                //后序遍历
                //s.push(p);
				//q.push(true);

				//s.push(p->right);
				//q.push(false);

				//s.push(p->left);
				//q.push(false);
			}
		}

		cout << "\n";
	}
}
Published 63 original articles · won praise 73 · views 70000 +

Guess you like

Origin blog.csdn.net/jjwwwww/article/details/86509590