查找二叉树中序遍历后继节点(java实现)

  • 问题描述
    查找某个节点的中序遍历的后继节点,没有则返回空。
  • 解决方案
    有三种情况:1.节点的右子树不为空,则返回右子树中最左的节点;2.节点的右子树为空且节点是父节点的左节点,则返回父节点即可;3.节点右子树为空且是父节点的右节点,则一直向上查找,直至找到某个节点是其父节点的左节点,返回该父节点,找不到则返回空。代码如下:
public class GetSuccessorNode {
    
    public static void main(String[] args){
        //测试如下二叉树
//                   1
//                /     \
//              2         3
//            /    \    /    \
//           4      5  6      7
        
        Node2 root = new Node2(1);
        root.left = new Node2(2);
        root.left.parent = root;
        root.left.left = new Node2(4);
        root.left.left.parent = root.left;
        root.left.right = new Node2(5);
        root.left.right.parent = root.left;
        root.right = new Node2(3);
        root.right.parent = root;
        root.right.left = new Node2(6);
        root.right.left.parent = root.right;
        root.right.right = new Node2(7);
        root.right.right.parent = root.right;
        System.out.println(getSuccessorNode(root.right).value);
    }

    //查找某个节点的中序遍历的后继节点,没有返回空
    public static Node2 getSuccessorNode(Node2 node){
        if(node == null)
            return null;
        if(node.right != null){
            node = node.right;
            while(node.left != null){
                node = node.left;
            }
            return node;
        }
        else if(node.parent.left  == node){
            return node.parent;
        }
        else{
            while(node.parent != null && node.parent.left != node){
                node = node.parent;
            }
            return node.parent;
        }
    }
}
class Node2{
    int value;
    Node2 left;
    Node2 right;
    Node2 parent;
    public Node2(int value){
        this.value = value;
        this.left = null;
        this.right = null;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值