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

问题

例子

思路

  • 方法1
    在这里插入图片描述

  • 方法2
    1: 如果该结点有右子树,则返回右子树最深的左子树
    在这里插入图片描述
    2:如果该结点没有右子树,不断向上找该结点的父结点。
    2.1:如果存在某个父节点,是其父节点的左子树,则返回其父节点
    在这里插入图片描述
    2.2:如果不存在某个父节点,是其父节点的左子树,则返回null
    在这里插入图片描述

代码

//方法1
import java.util.*;
public class Solution {
    private TreeLinkNode res = null;

    public TreeLinkNode GetNext(TreeLinkNode pNode)
    {
        TreeLinkNode node = pNode;
        while(node.next!=null) {
            node = node.next;
        }
        TreeLinkNode root=node;
        midOrder(root,pNode);
        return res;
    }
    public void midOrder(TreeLinkNode root, TreeLinkNode node) {
        if(root==null) return;

        if(root.left!=null) midOrder(root.left,node);
        if(root!=node && node.val<=root.val) {
            //只找第一个满足条件的,此时res为null
            if(res==null) {
                res=root;
            }
            return;


        }
        if(root.right!=null) midOrder(root.right,node);
    }
}
//方法2
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) {
            if(pNode.next.left==pNode) return pNode.next;
            pNode = pNode.next;
        }
        return null;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值