Populating Next Right Pointers in Each Node Total
Given a binary tree

struct TreeLinkNode {
      TreeLinkNode *left;
      TreeLinkNode *right;
      TreeLinkNode *next;
    }
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.

Note:

You may only use constant extra space.
You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
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

SOLUTION 1

我们可以用递归处理左右子树. 这个算法可能会消耗O(h)的栈空间。

 /* 试一下 recursion */
public void connect(TreeLinkNode root) {
if (root == null) {
return;
} rec(root);
} public void rec(TreeLinkNode root) {
if (root == null) {
return;
} if (root.left != null) {
root.left.next = root.right;
} if (root.right != null) {
root.right.next = root.next.left;
} rec(root.left);
rec(root.right);
}

2014.1229 redo:

 /*
3. A recursion version.
*/
public void connect3(TreeLinkNode root) {
if (root == null || root.left == null) {
return;
} root.left.next = root.right;
root.right.next = root.next == null ? null: root.next.left; connect(root.left);
connect(root.right);
}

SOLUTION 2

用层次遍历也可以相当容易解出来,而且这种方法用在下一题一点不用变。

但是 这个解法不能符合题意。题目要求我们使用 constant extra space.

 /*
* 使用level traversal来做。
* */
public void connect1(TreeLinkNode root) {
if (root == null) {
return;
} TreeLinkNode dummy = new TreeLinkNode(0);
Queue<TreeLinkNode> q = new LinkedList<TreeLinkNode>();
q.offer(root);
q.offer(dummy); while (!q.isEmpty()) {
TreeLinkNode cur = q.poll();
if (cur == dummy) {
if (!q.isEmpty()) {
q.offer(dummy);
}
continue;
} if (q.peek() == dummy) {
cur.next = null;
} else {
cur.next = q.peek();
} if (cur.left != null) {
q.offer(cur.left);
} if (cur.right != null) {
q.offer(cur.right);
}
}
}

 2014.1229 redo:

1.

 /*
1. Iterator.
*/
public void connect1(TreeLinkNode root) {
if (root == null) {
return;
} Queue<TreeLinkNode> q = new LinkedList<TreeLinkNode>();
q.offer(root); while (!q.isEmpty()) {
int size = q.size(); for (int i = 0; i < size; i++) {
TreeLinkNode cur = q.poll(); // ERROR 2: forget to determine if root don't have left and right.
if (cur.left == null) {
return;
} cur.left.next = cur.right;
cur.right.next = cur.next == null ? null : cur.next.left;
// bug 1: should put the offer inside the for loop
q.offer(cur.left);
q.offer(cur.right);
}
}
}

2.

 /*
2. Iterator. More simple version.
*/
public void connect2(TreeLinkNode root) {
if (root == null) {
return;
} Queue<TreeLinkNode> q = new LinkedList<TreeLinkNode>();
q.offer(root); while (!q.isEmpty()) {
int size = q.size(); for (int i = 0; i < size; i++) {
TreeLinkNode cur = q.poll(); // bug 1: should judge the size!
cur.next = (i == size - 1) ? null: q.peek(); if (cur.left != null) {
q.offer(cur.left);
q.offer(cur.right);
}
}
}
}

SOLUTION 3

把层次遍历修改一下,就是下面的解法了,我们使用2个循环,一个指针P1专门记录每一层的最左边节点,另一个指针P2扫描本层,把下一层的链接上。

下层链接完成后,将P1移动到它的左孩子即可。

这个算法的空间复杂度是O(1). 没有额外的空间。

 /*
The version that only has O(1) space complexity.
*/
public void connect(TreeLinkNode root) {
if (root == null) {
return;
} Iterator(root);
} public void Iterator(TreeLinkNode root) {
if (root == null) {
return;
} TreeLinkNode leftEnd = root; while(leftEnd != null) {
// go through the current level and link the next level.
TreeLinkNode cur = leftEnd;
while (cur != null) {
if (cur.left == null) {
break;
} cur.left.next = cur.right;
// 一定要记得判null.
cur.right.next = cur.next == null ? null: cur.next.left; cur = cur.next;
} // get to the next level.
leftEnd = leftEnd.left;
}
}

 2014.1229 redo:

 /*
4. Another constant iterator version.
*/
public void connect(TreeLinkNode root) {
if (root == null) {
return;
} TreeLinkNode leftEnd = root;
while (leftEnd != null && leftEnd.left != null) {
TreeLinkNode cur = leftEnd;
while (cur != null) {
cur.left.next = cur.right;
cur.right.next = cur.next == null ? null: cur.next.left; cur = cur.next;
} leftEnd = leftEnd.left;
}
}

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/tree/Connect_2014_1229.java

LeetCode: Populating Next Right Pointers in Each Node 解题报告的更多相关文章

  1. 【LeetCode】116. 填充每个节点的下一个右侧节点指针 Populating Next Right Pointers in Each Node 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcode ...

  2. LeetCode:Populating Next Right Pointers in Each Node I II

    LeetCode:Populating Next Right Pointers in Each Node Given a binary tree struct TreeLinkNode { TreeL ...

  3. [LeetCode] Populating Next Right Pointers in Each Node II 每个节点的右向指针之二

    Follow up for problem "Populating Next Right Pointers in Each Node". What if the given tre ...

  4. [LeetCode] Populating Next Right Pointers in Each Node 每个节点的右向指针

    Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *nex ...

  5. LeetCode——Populating Next Right Pointers in Each Node II

    Follow up for problem "Populating Next Right Pointers in Each Node". What if the given tre ...

  6. [leetcode]Populating Next Right Pointers in Each Node II @ Python

    原题地址:https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/ 题意: Follow up ...

  7. LeetCode: Populating Next Right Pointers in Each Node II 解题报告

    Populating Next Right Pointers in Each Node IIFollow up for problem "Populating Next Right Poin ...

  8. LEETCODE —— Populating Next Right Pointers in Each Node

    Populating Next Right Pointers in Each Node Given a binary tree struct TreeLinkNode { TreeLinkNode * ...

  9. LeetCode - Populating Next Right Pointers in Each Node II

    题目: Follow up for problem "Populating Next Right Pointers in Each Node". What if the given ...

随机推荐

  1. HDU 3974 Assign the task(dfs时间戳+线段树成段更新)

    题意:给定点的上下级关系,规定假设给i分配任务a.那么他的全部下属.都停下手上的工作,開始做a. 操作 T x y 分配x任务y,C x询问x的当前任务: Sample Input 1 5 4 3 3 ...

  2. 1、redis之安装与配置

    下载安装: redis-server.exe redis服务器的daemon启动程序 redis.conf redis配置文件 redis-cli.exe redis命令行操作工具.当然,也可以用te ...

  3. raise语句

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #Python学习手册 868 #raise语句 res=[IndexError,TypeError] #ra ...

  4. 关于free使用注意

    1,free的指针应该是通过 malloc calloc realloc 申请过内存的. 2,free的带有指针元素的结构体时要注意释放结构体的元素指针. 3,对于指向同一块内存的两个或多个指针,如果 ...

  5. 搭建Hexo博客并部署到Github

    参考: http://www.jianshu.com/p/a67792d93682 http://jingyan.baidu.com/article/d8072ac47aca0fec95cefd2d. ...

  6. web.xml文件头出错

    原先将web.xml文件头设置为如下格式 <?xml version="1.0" encoding="UTF-8"?><web-app ver ...

  7. HDUOJ---1863畅通工程

    畅通工程 Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submis ...

  8. python练习笔记——模拟双色球随机输出情况

    编写Python函数:完成一个双色球彩票的模拟生成过程, 其中前六个为蓝色球,数字范围1-33,不可重复.最后一个为红色球 1-16. 使用random完成,最后将7个数进行排列放到列表中 # 引入r ...

  9. OAF_OAF增删改-新增的实现(案例)

    2014-09-14 Created By BaoXinjian

  10. OkHttp拦截器的实现原理

    今天项目中遇到需要将从push接收到的数据按照协议parse成应用层需要的结构化数据类型问题:因为push消息类型繁多,等待解析出的结构化数据类型也多样,有的还需要经过几步的parse过程:而且因为项 ...