后序遍历非递归求结点的所有祖先(或求两个节点的最近公共祖先)

本文介绍了一种使用栈实现二叉树后序遍历的非递归方法,并展示了如何查找特定节点及其所有祖先节点的过程。此外,还探讨了如何寻找两个指定节点的最近公共祖先。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include "stdafx.h"
#include<cstdio>
#include<iostream>
#include<vector>
#include<stack>

using namespace std;
const int maxn=100;
struct node{
	int data;
	int tag;
	node*l,*r;};

	void postorder(node *root){//后序遍历的非递归写法
		node* p=root,*r=NULL;
		stack<node*>s;

		while(p||!s.empty()){
			if(p){
				s.push(p);
				p=p->l;

			}
			else{
				p=s.top();
				if(p->r&&p->r!=r){
					p=p->r;
				}
				else {s.pop();
				r=p;
				p=NULL;
				}
			}
		}
	}


	void search(node *root,int x){//求data为x的节点的所有祖先
		node* p=root;
		stack<node*>s;
		while(p||!s.empty()){
			while(p&&p->data!=x){
				s.push(p);
				p->tag=0;
				p=p->l;

			}
			if(p->data==x){
				while(!s.empty()){
					cout<<s.top()<<" ";
					s.pop();
				}
			}
			while(!s.empty()&&s.top()->tag==1){s.pop();}
			if(!s.empty()){s.top()->tag=1;p=s.top()->r;}
		}
	}


	node* ancestor(node *root,node *p,node *q){//求节点p和q的最近公共祖先,假设p在q的左边
		node* bt=root;
		stack<node*>s,s1;
		while(bt||!s.empty()){
			while(bt&&bt!=p&&bt!=q)
				while(bt){
					s.push(bt);
					bt->tag=0;
					bt=bt->l;}
				while(!s.empty()&&s.top()->tag==1){
					if(s.top()==p){
						s1=s;


					}
					if(s.top()==q){
                                         //遍历s1和s比较找到最近公共祖先即可

					}
					s.pop();

				}

				if(!s.empty()){s.top()->tag=1;
				bt=s.top()->r;}}

		return NULL


	}







	int main(){

		
		return 0;
	}


在C语言中,非递归节点的所有祖先通常涉及层次遍历(Level Order Traversal),特别是广度优先搜索(BFS)。这里我们可以创建一个队列来辅助存储节点及其层次,然后逐层取出节点并添加其父节点到结果数组。 以下是一个简单的示例代码: ```c #include <stdio.h> #include <stdlib.h> // 定义树节点结构体 typedef struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; } TreeNode; // 判断是否为空节点 int is_empty(TreeNode* node) { return node == NULL; } // 添加节点到队列 void enqueue(TreeNode* node, Queue* queue) { if (!is_empty(node)) { queue->tail->next = node; queue->tail = node; } } // 从队列中取出节点,并将其所有祖先添加到ancestors[]中 void get_ancestors(TreeNode* root, Queue* queue, int ancestors[], int level) { if (is_empty(root)) return; ancestors[level] = root->val; // 当前节点值添加到祖先数组 enqueue(root->left, queue); enqueue(root->right, queue); // 遍历左、右子节点直到空 while (!queue->empty()) { TreeNode* node = queue->front(); queue->dequeue(); // 取出下一个节点并继续查找祖先 get_ancestors(node, queue, ancestors, level + 1); } } // 主函数示例 int main() { TreeNode* tree = ... // 初始化树的数据结构 Queue queue; int ancestors[100]; // 假设最大层数不超过100 get_ancestors(tree, &queue, ancestors, 0); // 起始层级为0 for (int i = 0; i <= 100; ++i) { if (ancestors[i]) { printf("第 %d 层的祖先值: %d\n", i, ancestors[i]); } else { break; // 如果超过最大层数,停止打印 } } return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值