剑指offer 二叉树的下一个结点

题目

给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。

思路

  1. 当node的右子树不为空时,下一个结点为右子树最左结点。
  2. 当node的右子树为空时,下一个结点为最左的父节点。

代码

# -*- 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:
            pNode = pNode.right
            while pNode and pNode.left:
                pNode = pNode.left
            return pNode
        else:
            while pNode.next:
                if pNode.next.left == pNode:
                    return pNode.next
                pNode = pNode.next

猜你喜欢

转载自blog.csdn.net/y12345678904/article/details/80684793