-
Notifications
You must be signed in to change notification settings - Fork 0
/
find_TreeNode_by_stack.cpp
65 lines (53 loc) · 1.31 KB
/
find_TreeNode_by_stack.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
#include <stack>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
TreeNode *findNodeIterative(TreeNode *root, int target)
{
if (root == nullptr)
{
return nullptr;
}
stack< TreeNode * > s;
s.push(root);
while (!s.empty()) // stack isn't empty
{
TreeNode *node = s.top();
s.pop();
if (node->val == target)
return node;
// 右子树先入栈,深度优先搜索
// 因为先入栈,后出栈
if (node->right != nullptr)
s.push(node->right);
if (node->left != nullptr)
s.push(node->left);
}
return nullptr;
}
int main()
{
TreeNode *root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
int target = 5;
TreeNode *node = findNodeIterative(root, target);
if (node != nullptr)
{
cout << "Node found with value: " << node->val << endl;
} else
{
cout << "Node not found" << endl;
}
// 释放内存
// (在实际代码中,需要添加释放所有动态分配内存的代码)
return 0;
}