今天看到一个求二叉树中任意一个节点路径的题目,觉得有兴趣,所以写下了代码,记录下自己写的代码。
题目如下
C++ 代码
#include <iostream>
#include <vector>
#include <stack>
const int MAX_STACK_SIZE = 256;
enum LEAF_TYPE {
LEFT_LEAF,
RIGHT_LEAF,
LEFT_RIGHT_LEAF
};
struct Node {
Node* left{ nullptr };
int data;
Node* right{ nullptr };
};
void addLeaf(Node* node, LEAF_TYPE type,int &index)
{
if (node == nullptr) return;
Node* leaf = new Node();
leaf->data = index++;
if (type == LEFT_LEAF)
node->left = leaf;
else if (type == RIGHT_LEAF)
node->right = leaf;
else
{
node->left = leaf;
leaf = new Node();
leaf->data = index++;
node->right = leaf;
}
}
Node* buildTree()
{
int index = 1;
Node* root = new Node();
root->data = index++;
addLeaf(root, LEFT_RIGHT_LEAF, index);
addLeaf(root->left, RIGHT_LEAF, index);
addLeaf(root->right, RIGHT_LEAF, index);
addLeaf(root->right->right, LEFT_RIGHT_LEAF, index);
return root;
}
void freeTree(Node* root)
{
if (root == nullptr) return;
freeTree(root->left);
freeTree(root->right);
delete root;
}
//递归方法
bool lookupTree(Node* root, Node* p,int* Stack, int& position)
{
if (!root || !p || !Stack || position >=MAX_STACK_SIZE)
return false;
Stack[position++] = root->data;
if (root->data == p->data)
return true;
if (root->left)
{
if (lookupTree(root->left, p, Stack, position))
return true;
else
position--;
}
if (root->right )
{
if (lookupTree(root->right, p, Stack, position))
return true;
else
position--;
}
return false;
}
//非递归方法
bool lookupTree2(Node* root, Node* fp, int* Stack, int& position)
{
if (!root || !fp || !Stack || position >= MAX_STACK_SIZE)
return false;
if (root->data == fp->data)
{
Stack[position++] = root->data;
return true;
}
Node* tempStack[MAX_STACK_SIZE] = { nullptr };
int tempPos = 0;
auto p = root;
Node* lastVisited = nullptr;
while (tempPos > 0 || p != nullptr)
{
while (p != nullptr)
{
tempStack[tempPos++] = p;
Stack[position++] = p->data;
p = p->left;
}
auto node = tempStack[tempPos-1];
if (node->right == nullptr || node->right == lastVisited)
{
if (node->data == fp->data)
{
return true;
}
position--;
tempPos--;
lastVisited = node;
}
else
{
p = node->right;
}
}
return false;
}
int main()
{
Node* root = buildTree();
Node* p = root->right->right->right;
int Stack[MAX_STACK_SIZE] = { 0 };
int position = 0;
if (lookupTree2(root, p, Stack, position))
{
//Output Result
for (int i = 0; i < position; i++)
std::cout << Stack[i] << " ";
}
else
std::cout << "没有找到";
freeTree(root);
root = nullptr;
}