08 二叉树的下一个结点
题目
给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
上图二叉树的中序遍历是d,b,h,e,i,a,f,c,g
。我们以这棵树为例来分析如何找出二叉树的下一个结点。
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;
// 如果当前节点存在右子节点那么右子节点的最左子节点就是下一个节点
if(pNode->right)
{
pNode = pNode->right;
while(pNode->left != nullptr)
pNode = pNode->left;
return pNode;
}
// 如果当前节点没有右子节点,那么就要回溯其父节点
// 如果遇到了其父辈节点是一个左子节点那么就返回其父辈节点
while(pNode->next)
{
TreeLinkNode *pRoot = pNode->next;
if(pRoot->left == pNode)
return pRoot;
pNode = pNode->next;
}
return nullptr;
}
};
python 题解
# -*- 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 not pNode:
return None
if pNode.right:
pNode = pNode.right
while pNode.left:
pNode = pNode.left
return pNode
while pNode.next:
Parent = pNode.next
if Parent.left == pNode:
return Parent
pNode = pNode.next
return None