java 二叉树的下一个节点

牛客

  1. 简单暴力解法,从当前节点已知回溯到根节点,在由根节点中序遍历整个树,用 list 记录下来,最后在 list 中查找 pNode 的下一个节点
import java.util.*;
public class Solution {
    public ArrayList<TreeLinkNode> list = new ArrayList<>();
    public TreeLinkNode GetNext(TreeLinkNode pNode)
    {
        TreeLinkNode root = null, tmp = pNode;
        while (tmp != null) {
            root = tmp;
            tmp = tmp.next;
        }
        inOrder(root);
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i) == pNode && i + 1 != list.size()) 
                return list.get(i + 1);
        }
        return null;
    }
    
    public void inOrder(TreeLinkNode root) {
        if (root == null) return ;
        inOrder(root.left);
        list.add(root);
        inOrder(root.right);
    }
}
  1. 画一颗二叉树,写出中序遍历结果,分析每个节点与其下一个节点的关系,然后分类讨论,参考1 参考2
public TreeLinkNode GetNext(TreeLinkNode pNode) {
    if (pNode.right != null) { // 有右子树,下一个节点为右子树的最左边的节点
        TreeLinkNode node = pNode.right;
        while (node.left != null)
            node = node.left;
        return node;
    } else {
        while (pNode.next != null) { // 向上找父节点
            TreeLinkNode parent = pNode.next;
            if (parent.left == pNode) 
                return parent;
            pNode = pNode.next;
        }
    }
    return null;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值