美文网首页皮皮的LeetCode刷题库
【剑指Offer】057—二叉树的下一个结点(树)

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

作者: 就问皮不皮 | 来源:发表于2019-08-22 12:52 被阅读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

    相关文章

      网友评论

        本文标题:【剑指Offer】057—二叉树的下一个结点(树)

        本文链接:https://www.haomeiwen.com/subject/tllnsctx.html