剑指offer57-二叉树的下一个结点

题目描述

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

知识点回顾

代码

解法一:暴力循环

  1. 根据给出的结点求出整棵树的根节点
  2. 根据根节点递归求出树的中序遍历,存入vector
  3. 在vector中查找当前结点,则当前结点的下一结点即为所求。
# -*- 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
        tmp=pNode
        while tmp.next:                                #找到树的根节点
            tmp=tmp.next
        a=[]
        self.in_search(tmp,a)
        #if a.index(pNode)+1<=len(a)-1:
        #    return a[a.index(pNode)+1]
        #return None
        try:
            return a[a.index(pNode)+1]
        except:
            return None

    def in_search(self,tree,a):                  #注意这里有递归,所以不要在函数里定义a=[]
        if not tree:
            return None
        self.in_search(tree.left,a)
        a.append(tree)
        self.in_search(tree.right,a)

解法二:具体情况具体分析

举个中序遍历的图:如下:

图片说明
红色数字是中序遍历的顺序。接下来,我们就假设,如果当前结点分别是1,2 ... 7,下一结点看有什么规律没?

 
1
2
3
4
5
6
7
1 => 2 // 显然下一结点是 1 的父亲结点
2 => 3 // 下一节点是当前结点右孩子的左孩子结点,其实你也应该想到了,应该是一直到左孩子为空的那个结点
3 => 4 // 跟 2 的情况相似,当前结点右孩子结点的左孩子为空的那个结点
4 => 5 // 5 是父亲结点 3 的父亲结点,发现和1有点像,因为 1,3,同样是父亲结点的左孩子
5 => 6 // 跟 4=>5 一样的道理
6 => 7 // 跟 3=>4 一样的道理
7 => null // 因为属于最尾结点

此时,可以总结一下:
[1] 是一类:特点:当前结点是父亲结点的左孩子
[2 3 6] 是一类,特点:当前结点右孩子结点,那么下一节点就是:右孩子结点的最左孩子结点,如果右孩子结点没有左孩子就是自己
[4 5]是一类,特点:当前结点为父亲结点的右孩子结点,本质还是[1]那一类
[7]是一类,特点:最尾结点

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

 

 

posted @ 2020-12-13 12:16  foolangirl  阅读(87)  评论(0编辑  收藏  举报