题解 | #二叉树的下一个结点#

二叉树的下一个结点

http://www.nowcoder.com/practice/9023a0c988684a53960365b889ceaf5e

# -*- coding:utf-8 -*-
#discuss according to different cases
# 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
        #1-if pNone==None
        if pNode==None:
            print("null")
            return None
        #2-if pNone is not final leaf node:
        if pNode.right !=None:
            pNode=pNode.right
            while pNode.left != None:
                pNode=pNode.left
            return pNode
        elif pNode.next!=None:
            if pNode==pNode.next.left:
                return pNode.next
            elif pNode==pNode.next.right:
                pNode=pNode.next
                if pNode.next==None:
                    return None
                while pNode!=pNode.next.left:
                    pNode=pNode.next
                    if pNode.next==None:
                        return None
                return pNode.next
#                 print("null")
                return None
                
#         print("null")
#         return None


这道题思路很简单,就是分情况讨论:
1) 若节点有右子节点/右子树时,它的下一个节点是右子树的叶子左节点;
2)若节点无右子树时--->判断它是左节点还是右节点:是左节点(即pNode==pNode.next.left),下一个节点为它的父节点; 不是左节点(则是右节点),则要沿着指针向上不断找父节点,直到这个大子树的根节点,即pNode==pNode.next.left

考虑边界测例:
节点为None时,返回None;
节点是整个树最后一个右叶子节点时,返回None
该树只有一个节点时(即pNode.next==None),返回None

全部评论

相关推荐

点赞 评论 收藏
分享
07-03 11:02
中山大学 C++
字节刚oc,但距离九月秋招很近了有两段互联网实习,非腾讯字节。不敢赌转正,现在在纠结去还是不去如果实习俩月离职会有什么后果吗
阿城我会做到的:不去后悔一辈子,能否转正取决于ld的态度,只要他不卡,答辩就是走流程,个人觉得可以冲一把
投递字节跳动等公司8个岗位
点赞 评论 收藏
分享
认真搞学习:28小登的建议,投算法岗不要写什么物理竞赛,互联网+,多写点项目,用什么算法做了什么。还有本科算法是不可能的开发你这个也没有项目啊
点赞 评论 收藏
分享
深夜书店vv:腾讯是这样的,去年很多走廊都加桌子当工区
点赞 评论 收藏
分享
榕城小榕树:1200单休,我去干点啥别的不好
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务