出鞘之剑指offer-第8题 (二叉树的下一个节点)

题目:

 给定一棵二叉树和其中一个节点,如何找出中序遍历序列的下一个节点?树中的节点除了有两个分别指向左、右子节点的指针,还有一个指向父节点的指针。

分析一: 

(1)如果一个节点有右子树,那下一个节点就是它右子树的最左子节点。

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

        (a)如果这个节点是其父节点的左子节点,那下一个节点就是其父节点。

        (b)如果这个节点是其父节点的右子节点,就必须沿着指向父节点的指针向上遍历,知道找到是父节点的左子节点的节点,              那下一个节点就是其父节点。

代码一: 

package offer.xzs.eighth;

public class NextNode01 {
    public static void main(String[] args) {
        BinaryTree root = new BinaryTree();
        BinaryTree node2 = new BinaryTree();
        BinaryTree node3 = new BinaryTree();
        BinaryTree node4 = new BinaryTree();
        BinaryTree node5 = new BinaryTree();
        root.setValue(1);
        root.setLeft(node2);
        root.setRight(node3);
        root.setFather(null);
        node2.setFather(root);
        node2.setValue(2);
        node2.setLeft(node4);
        node2.setRight(node5);
        node3.setValue(3);
        node3.setFather(root);
        node3.setRight(null);
        node3.setLeft(null);
        node4.setValue(4);
        node4.setFather(node2);
        node4.setRight(null);
        node4.setLeft(null);
        node5.setValue(5);
        node5.setFather(node2);
        node5.setRight(null);
        node5.setLeft(null);
        midOrder(root);
        System.out.println();
        BinaryTree binaryTree = nextNode(node5);
        System.out.println(binaryTree.getValue());

    }

    public static BinaryTree nextNode(BinaryTree node) {
        if (node == null) {
            return null;
        }
        if (node.getRight() != null) {
            BinaryTree result = node.getRight();
            while (result.getLeft() != null) {
                result = result.getLeft();
            }
            return result;
        } else {
            while (node.getFather() != null) {
                if (node.getFather().getLeft() == node) {
                    return node.getFather();
                }
                node = node.getFather();
            }
        }
        return null;
    }

    public static void midOrder(BinaryTree root) {
        if (root == null) {
            return;
        }
        if (root.getLeft() != null) {
            midOrder(root.getLeft());
        }
        System.out.printf("%d\t", root.getValue());
        if (root.getRight() != null) {
            midOrder(root.getRight());
        }
    }

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值