面试8:找二叉树的下个结点
关键是举例和画图的思想。
主要分三种类型。
1.有右子树:返回 右子树的最左节点。
2.无右子树:2.有父节点:2.是左结点:返回 父节点。
3.无右子树:3.有父节点:3.是右节点:找到第一个是左结点的节点,返回 该节点的父节点。//这里的while我出了个bug
4.无右子树:4.无父节点:返回 空。
我的代码。
/*
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* pnext = nullptr;
//有右子树
if(pNode->right != nullptr)
{
pnext = pNode->right;
while(pnext->left != nullptr)
pnext = pnext->left;
}
//无右子树
else
{
//有父节点
if(pNode->next != nullptr)
{
TreeLinkNode* parent = pNode->next;
//是左子树
if(pNode == parent->left) pnext = parent;
//是右子树
else if(pNode == parent->right)
{
TreeLinkNode* current = pNode;
parent = current->next;
while(parent != nullptr && current == parent->right)
{
current = current->next;
parent = current->next;//bug1这里父节点也变了
}
pnext = current->next;
}
}
//无父结点
else
{
pnext = nullptr;
}
}
return pnext;
}
};
网友的python代码
#1.有右子树,返回 右子树最左边的结点
#2.无右子树,返回 当前结点成为左子树跟时的父节点
# -*- coding:utf-8 -*-
# class TreeLinkNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.next = None
class Solution:
def GetNext(self, pNode):
# write code here
if pNode is None:
return None
#1.有右子树,为右子树最左边的结点
if pNode.right is not None:
node=pNode.right
while node.left is not None:
node=node.left
return node
#2.无右子树,为当前结点成为左子树跟时的父节点
if pNode.next is not None:
cur_node=pNode
parent_node=pNode.next
while parent_node is not None and parent_node.left!=cur_node:
cur_node=parent_node
parent_node=cur_node.next
return parent_node
return None
第二种思路
如果无右子树且父节点存在,只要找到为左结点的节点就好了,返回该节点的父节点。
class Solution:
def GetNext(self, pNode):
# write code here
if pNode is None:
return None
if pNode.right is not None:
pNode = pNode.right
while pNode.left is not None:
pNode = pNode.left
return pNode
while pNode.next is not None:
if pNode.next.left == pNode:
return pNode.next
pNode = pNode.next
return None