找出二叉树中某个节点的所有祖先节点

对于一颗普通的二叉树和一个节点key,找出该节点的所有祖先节点。

例如树结构如下:给定的key为节点7,则应该打印 4,2,1。

       1
        /   \
      2      3
    /  \
  4     5
 /
7

使用递归可以很容易的解决,代码如下:

#include<iostream>

using namespace std;

struct Node
{
	int data;
	Node* lChild;
	Node* rChild;
	Node(int _data) { data = _data; lChild = rChild = nullptr; }
};

bool PrintAncestors(Node* _root, int target)
{
	if (!_root) return false;
	if (_root->data == target) return true;

	//子树可以找到,当前节点肯定为祖先节点
	if (PrintAncestors(_root->lChild, target) || PrintAncestors(_root->rChild, target))
	{
		cout << _root->data << " ";
		return true;
	}

	return false;
}

Node* NewNode(int _data)
{
	Node* node = new Node(_data);
	return node;
}

int main()
{
/*创建下面的二叉树

	      1
		 / \
	    2   3
	   / \
	  4   5
	 /
	7

*/

	Node* root = NewNode(1);
	root->lChild = NewNode(2);
	root->rChild = NewNode(3);
	root->lChild->lChild = NewNode(4);
	root->lChild->rChild = NewNode(5);
	root->lChild->lChild->lChild = NewNode(7);

	PrintAncestors(root, 7);// output: 4 2 1
	cout << endl;

	return 0;
}








题目来自: http://www.acmerblog.com/ancestors-of-a-given-node-6048.html


下面是C#实现二叉树节点的所有祖先节点的源代码: ```csharp using System; using System.Collections.Generic; namespace BinaryTreeAncestor { public class Node { public int Value { get; set; } public Node LeftChild { get; set; } public Node RightChild { get; set; } public Node(int value) { Value = value; } //获取当前节点的所有祖先节点 public List<Node> GetAncestors() { List<Node> ancestors = new List<Node>(); Node current = this; while (current != null) { ancestors.Add(current); current = current.Parent; } return ancestors; } //获取当前节点的父节点 public Node Parent { get; set; } } class Program { static void Main(string[] args) { Node root = new Node(1) { LeftChild = new Node(2) { LeftChild = new Node(4), RightChild = new Node(5) }, RightChild = new Node(3) { LeftChild = new Node(6), RightChild = new Node(7) } }; List<Node> ancestors = root.LeftChild.RightChild.GetAncestors(); Console.WriteLine("节点{0}的祖先节点为:", root.LeftChild.RightChild.Value); foreach (Node node in ancestors) { Console.Write(node.Value + " "); } Console.ReadLine(); } } } ``` 在该实现,我们为节点类添加了一个`Parent`属性,表示当前节点的父节点。然后在`GetAncestors`方法,我们使用一个`while`循环来遍历当前节点的所有祖先节点,每次将当前节点加入到祖先节点列表,并将当前节点更新为其父节点,直到当前节点为`null`(即已经遍历到根节点)。最后,在`Main`方法,我们测试了获取二叉树某个节点的所有祖先节点的功能。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值