JZ8 二叉树的下一个结点

JZ8 二叉树的下一个结点

题源 👉二叉树的下一个结点_牛客题霸_牛客网 (nowcoder.com)

题目描述:

image-20230218130300007

image-20230218130324990

image-20230218130350332

具体实现:

方法一:递归 👉 二叉树的下一个结点_牛客博客 (nowcoder.net)

image-20230218130134414

import java.util.*;
public class Solution {
    ArrayList<TreeLinkNode> nodes = new ArrayList<>();
    public TreeLinkNode GetNext(TreeLinkNode pNode) {
        // 获取根节点
        TreeLinkNode root = pNode;
        while(root.next != null) root = root.next;
        
        // 中序遍历打造nodes
        InOrder(root);
        
        // 进行匹配
        int n = nodes.size();
        for(int i = 0; i < n - 1; i++) {
            TreeLinkNode cur = nodes.get(i);
            if(pNode == cur) {
                return nodes.get(i+1);
            }
        }
        return null;
    }
    
    // 中序遍历
    void InOrder(TreeLinkNode root) {
        if(root != null) {
            InOrder(root.left);
            nodes.add(root);
            InOrder(root.right);
        }
    }
}

时间:O(n)

空间:O(n)


方法二:分类寻找 👉 二叉树的下一个结点_牛客博客 (nowcoder.net)

(第三种情况本人没考虑到,看了官方题解)

image-20230218125916484

/*
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.right != null){
            TreeLinkNode p = pNode.right;
            while(p.left != null) p = p.left;
            return p;
        }

        // 右子树不存在,当前pNode为其父结点的左结点
        if(pNode.next != null && pNode.next.left == pNode){
            return pNode.next;
        }

        // 右子树不存在,当前pNode为其父结点的右结点,
        // 沿左上方父结点爬树,直到爬到当前结点是其父结点的左节点为止,返回 这个父结点
        if(pNode.next != null){
            TreeLinkNode p = pNode.next;
            while(p.next != null && p.next.right == p) p = p.next;
            return p.next;
        }
        return null;
    }
}

时间:O(n)

空间:O(1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值