LeetCode - Populating Next Right Pointers in Each Node II
2016-01-13 15:41
567 查看
题目:
Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
You may only use constant extra space.
For example,
Given the following binary tree,
After calling your function, the tree should look like:
思路:
递归,对root的左右进行连接操作,然后先递归右树,再递归左树。
Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
You may only use constant extra space.
For example,
Given the following binary tree,
1 / \ 2 3 / \ \ 4 5 7
After calling your function, the tree should look like:
1 -> NULL / \ 2 -> 3 -> NULL / \ \ 4-> 5 -> 7 -> NULL
思路:
递归,对root的左右进行连接操作,然后先递归右树,再递归左树。
package tree; public class PopulatingNextRightPointersInEachNodeII { public void connect(TreeLinkNode root) { if (root == null || (root.left == null && root.right == null)) return; TreeLinkNode next = root.next; while (next != null) { if(next.left != null) { next = next.left; break; } if (next.right != null) { next = next.right; break; } next = next.next; } if (root.right != null) root.right.next = next; if (root.left != null) root.left.next = root.right == null ? next : root.right; connect(root.right); connect(root.left); } }
相关文章推荐
- nodejs系列(一)安装和介绍
- hadoop2解决 NameNode 单点故障问题的 高可用集群配置
- nodesj中 中间件express-session的理解
- LeetCode - Populating Next Right Pointers in Each Node
- nodejs path
- nodejs关于session和cookie的问题
- 记一次DataNode慢启动问题
- Node.js基础学习
- node.js初识
- 解决Postman发送post数据但是Node.js中req.body接收不到数据的问题
- [Mac]解决Yosemite下iNode客户端上网问题
- [leetcode] 117. Populating Next Right Pointers in Each Node II 解题报告
- 用Node操作Firebird。
- Node.js_全局对象
- hadoop多次格式化后导致VERSION不一致,启动namenode和datanode时报错的解决方法
- nodejs Tips7
- Hello NodeJS
- 汇智网node学习笔记
- React-Native 获取node.js提供的接口
- 呜呼!Node.js是什么?