-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path二叉树的下一个节点.cpp
46 lines (35 loc) · 1.04 KB
/
二叉树的下一个节点.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
//给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。
//注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
/*
struct TreeLinkNode {
int val;
struct TreeLinkNode *left;
struct TreeLinkNode *right;
struct TreeLinkNode *next;
TreeLinkNode(int x) :val(x), left(NULL), right(NULL), next(NULL) {
}
};
*/
class Solution {
public:
TreeLinkNode* GetNext(TreeLinkNode* pNode)
{
if (!pNode)
return nullptr;
if (pNode->right) {
pNode = pNode->right;
while (pNode->left)
pNode = pNode->left;
return pNode;
}
TreeLinkNode* pre = pNode;
pNode = pNode->next;
while (pNode && pNode->right == pre) {
pre = pNode;
pNode = pNode->next;
}
if (!pNode)
return nullptr;
return pNode;
}
};