给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
思路:
失败:
刚开始想着先看根,再看叶子结点,再看中间。这样就没有结合题目,很麻烦了。
正确:
中序,有没有右子树,有的话,必须找右子树的最左边的节点。
如果有根节点,那么得分是左子节点(直接返回父节点)
右子节点--------一直找父节点,如果父节点是右子节点,继续找,如果是左子节点,就返回这个节点的父节点~~~
如果过程中找到了根节点,那么就直接返回null。
/*
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){
pNode=pNode->right;
while(pNode->left)
pNode=pNode->left;
return pNode;
}
else{
if(pNode->next==NULL)//根
return NULL;
if(pNode->next->left==pNode)//左叶子
return pNode->next;
else if(pNode->next->right==pNode){//右叶子
TreeLinkNode* tmp=pNode;
while(tmp->next->right==tmp)
{
tmp=tmp->next;
if(tmp->next==NULL||tmp==NULL){
return NULL;
}
}
return tmp->next;
}
}
return NULL;
}
};
/*
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;
}
if(pNode.right!=null){
pNode = pNode.right;
while(pNode.left!=null){
pNode = pNode.left;
}
return pNode;
}else{
if(pNode.next ==null){
return null;
}
if(pNode.next!=null){
if(pNode.equals(pNode.next.left)){
return pNode.next;
}else{
while(pNode.equals(pNode.next.right)){
pNode = pNode.next;
if(pNode.next==null){
return null;
}
}
return pNode.next;
}
}
}
return null;
}
}