本文主要是介绍populating-next-right-pointers-in-each-node-ii,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1、populating-next-right-pointers-in-each-node-ii 来源:牛客网
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 7After calling your function, the tree should look like:1 -> NULL/ \2 -> 3 -> NULL/ \ \4-> 5 -> 7 -> NULL
2、思路:
- 代码1思路,采用队列,对于每一层的元素,遍历时,用一个临时的结点cur放置当前poll出来的结点,poll后,检查当前队列的对头是否是该层元素,若是用cur指向就可以了;
- 代码2思路,不使用队列(题目说是You may only use constant extra space)。首先不使用队列的情况下我们要遍历整个树,就得利用它每一层都有一条链,有链就可以通过一个结点遍历一层了。这里通过新建头部结点tmpLevelFirst(该结点本身的值和树没关系,只有tmpLevelFirst.next来指向每一层的头结点)来实现
3、代码1,用队列辅助实现:
public class BFSConnectTree {public void connect(TreeLinkNode root) {if(root == null)return;Queue<TreeLinkNode> queue = new LinkedList<TreeLinkNode>();queue.add(root);TreeLinkNode node = new TreeLinkNode(0);while(!queue.isEmpty()){int broad_size = queue.size();//每一层 的节点数目for(int i = 0; i < broad_size; i++){node = queue.poll();if(i == broad_size - 1){//若是当前层的最后一个元素手动指向nullnode.next = null;}else{node.next = queue.peek();}if(node.left != null)queue.add(node.left);if(node.right != null)queue.add(node.right);}}}}
代码2,利用每层都是链的特点实现:
public class BFSConnectTreeWithoutSpace {public void connect(TreeLinkNode root) {while (root != null) {//tmpLevelFirst为新建立的每层第一个节点(为了方便后面遍历当前行节点)TreeLinkNode tmpLevelFirst = new TreeLinkNode(0);TreeLinkNode cur = tmpLevelFirst;while (root != null) {if (root.left != null) {cur.next = root.left;cur = cur.next;}if (root.right != null) {cur.next = root.right;cur = cur.next;}root = root.next;}root = tmpLevelFirst.next;}}
}
注:代码和思路都参考了上面链接中的答案,非常感谢那些大佬
这篇关于populating-next-right-pointers-in-each-node-ii的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!