问题:给定一个节点,找出中序遍历的下一个节点。
直接看下面的Solution2
这个题要认真分析一下。。。
Solution1:
自己想出来的破算法
/*
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) { //中序遍历:左根右;
//case1:最简单的情况
if(pNode == NULL) //空指针,返回NULL
return NULL;
//case2:pNode无父结点的情况
TreeLinkNode *temp;
if(pNode->next == NULL) {
if(pNode->right) { //有右子结点!
temp = pNode->right;
while(temp->left != NULL)
temp = temp->left;
return temp;
}
else
return NULL;
}
//case3:pNode是父结点的左子结点
if(pNode == pNode->next->left) {
if(pNode->right) { //有右子结点!
temp = pNode->right;
while(temp->left != NULL)
temp = temp->left;
return temp;
}
else
return pNode->next;
}
//case4:pNode是父结点的右子结点,最麻烦
if(pNode == pNode->next->right) {
if(pNode->right) {//是父结点的右子结点且有右子结点
temp = pNode->right;
while(temp->left != NULL)
temp = temp->left;
return temp;
}
else { //是父结点的右子结点但没有右子结点,有点麻烦了。。
temp = pNode->next; //把temp指针指向当前结点的父结点
while(temp->next != NULL) {
if(temp == temp->next->left)
return temp->next;
else
temp = temp->next;
}
return NULL;
}
}
return NULL;
}
};
Solution2:
参考网址:https://www.nowcoder.com/profile/2044032/codeBookDetail?submissionId=19265891
分析二叉树的下一个节点,一共有以下情况:
1.二叉树为空,则返回空;
2.节点右孩子存在,则设置一个指针从该节点的右孩子出发,一直沿着指向左子结点的指针找到的叶子节点即为下一个节点;
3.节点不是根节点。如果该节点是其父节点的左孩子,则返回父节点;否则继续向上遍历其父节点的父节点,重复之前的判断,返回结果。代码如下:
这样想思路更清晰,代码更简洁~
/*
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==NULL)
return NULL;
if(pNode->right!=NULL)
{
pNode=pNode->right;
while(pNode->left!=NULL)
pNode=pNode->left;
return pNode;
}
while(pNode->next!=NULL)
{
TreeLinkNode *proot=pNode->next;
if(proot->left==pNode)
return proot;
pNode=pNode->next;
}
return NULL;
}
};
20180911日,按照solution2的方案重新写一下
/*
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 NULL;
if (pNode->right) { // 有右子树
TreeLinkNode *cur = pNode->right;
while (cur->left)
cur = cur->left;
return cur;
} else { //没有右子树
while (pNode->next) {
TreeLinkNode *pRoot = pNode->next;
if (pRoot->left == pNode)
return pRoot;
pNode = pNode->next;
}
return NULL;
}
}
};