在一个二叉树中查找一个节点的后继节点

后继节点:在中序遍历中一个节点的下一个节点

二叉树类型如下:

 public static class Tree {
        private int number;
        private Tree leftNode;
        private Tree rightNode;
        private Tree parent;

        public Tree(int number, Tree leftNode, Tree rightNode, Tree parent) {
            this.number = number;
            this.leftNode = leftNode;
            this.rightNode = rightNode;
            this.parent = parent;
        }
    }

如果一个节点有右子树,则其后继节点为其右子树上的最左的节点。

如果一个节点没有右子树:

1、如过该节点为其父节点的左子树,则其后继节点为其父节点

2、如过该节点为其父节点的右子树、则遍历其父节点(包括其父节点的父节点),如果某个节点的左子树是其父节点(包括其父节点的父节点),则其后继节点为该节点。


public class TreeNode {

    public static class Node {
        private int number;
        private Node leftNode;
        private Node rightNode;
        private Node parent;

        public Node(int number, Node leftNode, Node rightNode) {
            this.number = number;
            this.leftNode = leftNode;
            this.rightNode = rightNode;
        }
    }


    public static void creadNodeNode() {
        Node Node7 = new Node(7, null, null);
        Node Node6 = new Node(6, null, null);
        Node Node5 = new Node(5, null, null);
        Node Node4 = new Node(4, null, null);
        Node Node3 = new Node(3, Node6, Node7);
        Node Node2 = new Node(2, Node4, Node5);
        Node Node1 = new Node(1, Node2, Node3);
        Node1.parent = null;
        Node2.parent = Node1;
        Node3.parent = Node1;
        Node4.parent = Node2;
        Node5.parent = Node2;
        Node6.parent = Node3;
        Node7.parent = Node3;
        getNodeNext(Node7);

    }

    public static void getNodeNext(Node node) {

        if (null == node) {
            return;
        }
        if (null != node.rightNode) {
            Node nodeLeft = getNodeLeft(node.rightNode);
            System.out.println(nodeLeft.number);
        } else {
            Node p = node.parent;
            while (null != p && p.leftNode != node) {
                node = p;
                p = node.parent;
            }
            if (null != p) {
                System.out.println(p.number);
            }
        }
    }


    public static Node getNodeLeft(Node node) {
        if (null == node) {
            return null;
        }
        while (null != node.leftNode) {
            node = node.leftNode;
        }
        return node;
    }

    public static void main(String[] args) {
        creadNodeNode();
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值