116. Populating Next Right Pointers in Each Node

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL
For example,
Given the following perfect binary tree,
1
/
2 3
/ \ /
4 5 6 7
After calling your function, the tree should look like:
1 -> NULL
/
2 -> 3 -> NULL
/ \ /
4->5->6->7 -> NULL

这题我一开始想用queue那套来做发现比较难。然后看了leetcode里面一个人的答案,感觉非常tricky。。简单说就是cur在本层向右走,pre向下一层的第一个node走。尤其那句:cur.right.next = cur.next.left;,需要画个图来看会比较清楚。还有两层while的条件也很巧妙。

这种题好像没有套路可寻,感觉不太好在面试的时候想到这样的解法。

    public void connect(TreeLinkNode root) {
        if (root == null) return;

        TreeLinkNode pre = root;
        TreeLinkNode cur = null;
        while (pre.left != null) {
            cur = pre;
            while (cur != null) {
                //pre.left!=null保证了cur.left不为Null
                cur.left.next = cur.right;
                //无形中把下一层的最左边的node跟右边连接起来了
                if (cur.next != null) {
                    cur.right.next = cur.next.left;
                }
                cur = cur.next;
            }
            pre = pre.left;
        }
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容