Java查找二叉树中序遍历节点的下一个节点(剑指offer面试题8)

接上一篇博客,直接上代码吧

节点类
package swordoffer.binarytree;

/**
 * @program: javaStudyTest
 * @description: 二叉树与二叉树重建
 * @create: 2020-03-03
 **/
public class BinaryTreeNode<E> {
    //数据部分
    private E item;
    //父亲节点
    BinaryTreeNode<E> fatherNode;
    //左子节点
    BinaryTreeNode<E> leftChildNode;
    //右子节点
    BinaryTreeNode<E> rightChildNode;


    public BinaryTreeNode(E item) {
        this.item = item;
    }
}
二叉树工具类,查找下一个节点算法
package swordoffer.binarytree;

import org.apache.commons.lang3.ArrayUtils;
import java.util.Arrays;

/**
 * @program: javaStudyTest
 * @description: 重建二叉树
 * @create: 2020-03-03
 **/
public class BinaryTreeUtils<T> {
	/**
     * 查找二叉树中的中序遍历的下一个节点(有子节点指向父节点指针的情况)
     *
     * @param node
     * @return
     */
    private BinaryTreeNode<T> getNextNode(BinaryTreeNode<T> node) {
        if (node == null) return null;
        BinaryTreeNode<T> nextNode = null;

        //节点存在右子树
        if (node.rightChildNode != null) {
            BinaryTreeNode<T> tempNode = node.rightChildNode;
            while (tempNode.leftChildNode != null) {
                tempNode = tempNode.leftChildNode;
            }
            nextNode = tempNode;
        } else if (node.fatherNode != null) { //不存在右子树,存在父节点
            //如果该节点是其父节点的左子节点
            if (node.fatherNode.leftChildNode == node) {
                nextNode = node.fatherNode;
            } else { //该节点是其父节点的右子节点
                BinaryTreeNode<T> tempNode = node.fatherNode;
                while (tempNode.fatherNode != null && tempNode.fatherNode.rightChildNode == tempNode) { //该节点存在父节点,且为该父节点的右子节点
                    tempNode = tempNode.fatherNode;
                }
                nextNode = tempNode.fatherNode; // 因为父节点为空而退出循环,或因为是父节点的左子节点而退出循环
            }
        }
        return nextNode;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值