皮皮的LeetCode刷题库

【剑指Offer】057—二叉树的下一个结点(树)

2019-08-22  本文已影响1人  就问皮不皮

题目描述

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

解题思路

file

中序遍历:左 -> 根 -> 右
分三种情况:

如果当前节点有右子树,则返回右子树的最左子树(既到根-->右);第一种情况。

如果当前节点没有右子树,再分两种情况:

参考代码

Java

/*
public class TreeLinkNode {
    int val;
    TreeLinkNode left = null;
    TreeLinkNode right = null;
    TreeLinkNode next = null;

    TreeLinkNode(int val) {
        this.val = val;
    }
}
*/
public class Solution {
    public TreeLinkNode GetNext(TreeLinkNode pNode)
    {
        // 边界
        if(pNode == null){
            return null;
        }
        // 第一种情况
        if(pNode.right != null){
            TreeLinkNode node = pNode.right;
            while(node.left != null){
                node = node.left;
            }
            return node;
        }
        // 第二和第三种情况
        while(pNode.next != null){
            TreeLinkNode root = pNode.next; // 父节点
            if(pNode == root.left)
                return root;
            pNode = root;
        }
        return null;
    }
}

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:
            node = pNode.right
            while node.left:
                node = node.left
            return node
        # 当前结点没有右子树
        while pNode.next:
            # pNode的父节点
            root = pNode.next
            # 当前结点是父节点的左子树,第二种情况
            if pNode == root.left:
                return root
            pNode = root
        return None

个人订阅号

image
上一篇下一篇

猜你喜欢

热点阅读