对于一颗普通的二叉树和一个节点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