题目描述
给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
代码
c++:
/*
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 == nullptr)
return nullptr;
TreeLinkNode* nextNode = nullptr;
if(pNode->right != nullptr){
TreeLinkNode* rightNode = pNode->right;
while( rightNode->left != nullptr)
rightNode = rightNode->left;
nextNode = rightNode;
}
else if(pNode->next != nullptr){
TreeLinkNode* parentNode = pNode->next;
TreeLinkNode* currentNode = pNode;
while(parentNode != nullptr && currentNode == parentNode->right){
currentNode = parentNode;
parentNode = parentNode->next;
}
nextNode = parentNode;
}
return nextNode;
}
};
java:
/*
public class TreeLinkNode {
int val;
TreeLinkNode left = null;
TreeLinkNode right = null;
TreeLinkNode next = null;
TreeLinkNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public TreeLinkNode GetNext(TreeLinkNode pNode)
{
if(pNode == null)
return null;
TreeLinkNode nextNode = null;
if(pNode.right != null){
TreeLinkNode rightNode = pNode.right;
while(rightNode.left != null)
rightNode = rightNode.left;
nextNode = rightNode;
}
else if(pNode.next != null){
TreeLinkNode currentNode = pNode;
TreeLinkNode parentNode = pNode.next;
while(parentNode != null && currentNode == parentNode.right){
currentNode = parentNode;
parentNode = parentNode.next;
}
nextNode = parentNode;
}
return nextNode;
}
}