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 pNode.right is not None:
            root=pNode.right
            while(root.left is not None):
                root=root.left
            return root
        else:
            # 如果当前节点的父节点的左孩子是当前节点,则直接返回当前节点的父节点
            if pNode.next is None:
                return None
            if pNode.next.left==pNode:
                return pNode.next
            while(pNode.next and pNode.next.right==pNode):
                pNode=pNode.next
            return pNode.next

猜你喜欢

转载自blog.csdn.net/WYXHAHAHA123/article/details/89920600