首页 > 其他 > 详细

在每个节点填充向右的指针 Populating Next Right Pointers in Each Node

时间:2018-08-09 19:13:53      阅读:163      评论:0      收藏:0      [点我收藏+]

2018-08-09 16:01:40

一、Populating Next Right Pointers in Each Node

问题描述:

技术分享图片

技术分享图片

问题求解:

由于是满二叉树,所以很好填充。

    public void connect(TreeLinkNode root) {
        if (root != null) {
            if (root.left != null) root.left.next = root.right;
            if (root.right != null && root.next != null) root.right.next = root.next.left;
            connect(root.left);
            connect(root.right);
        }
    }

 

二、Populating Next Right Pointers in Each Node II

问题描述:

技术分享图片

技术分享图片

问题求解:

本题中因为不再是满二叉树,因此不能简单的使用先序遍历进行求解,因为先序遍历是有先后顺序的,因此单纯采用先序遍历会出现丢失的现象。因此只能使用按行求解。

    public void connect(TreeLinkNode root) {
        if (root == null) return;
        TreeLinkNode dummy = new TreeLinkNode(-1);
        for (TreeLinkNode cur = root, pre = dummy; cur != null; cur = cur.next) {
            if (cur.left != null) {
                pre.next = cur.left;
                pre = pre.next;
            }
            if (cur.right != null) {
                pre.next = cur.right;
                pre = pre.next;
            }
        }
        connect(dummy.next);
    }

 

在每个节点填充向右的指针 Populating Next Right Pointers in Each Node

原文:https://www.cnblogs.com/TIMHY/p/9450905.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!