Leetcode: Populating Next Right Pointers in Each Node II

王朝学院·作者佚名  2016-05-29
窄屏简体版  字體: 小  |  中  |  大  |  超大  

Leetcode: Populating Next Right Pointers in Each Node IIFollow 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

在Populating Next Right Pointers in Each Node问题的基础上,难度20,方法一样。都是类似Binary Tree Level Order Traverse,都是把树看成一个无向图,然后用BFS的方式,需要记录每一层的ParentNumInQueue以及ChildNumInQueue, 初始值为1和0,以后每次ParentNumInQ减至0说明这一层已经遍历完毕,这一层的Child数将成为下一层的ParentNumInQ

1 /** 2 * Definition for binary tree with next pointer. 3 * public class TreeLinkNode { 4 * int val; 5 * TreeLinkNode left, right, next; 6 * TreeLinkNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution {10 public void connect(TreeLinkNode root) {11 if (root == null) return;12 LinkedList<TreeLinkNode> queue = new LinkedList<TreeLinkNode>();13 queue.add(root);14 int ParentNumInQ = 1;15 int ChildNumInQ = 0;16 TreeLinkNode pre = null;17 while (!queue.isEmpty()) {18 TreeLinkNode cur = queue.poll();19 ParentNumInQ--;20 if (pre == null) {21 pre = cur;22 }23 else {24 pre.next = cur;25 pre = pre.next;26 }27 if (cur.left != null) {28 queue.add(cur.left);29 ChildNumInQ++;30 }31 if (cur.right != null) {32 queue.add(cur.right);33 ChildNumInQ++;34 }35 if (ParentNumInQ == 0) {36 ParentNumInQ = ChildNumInQ;37 ChildNumInQ = 0;38 pre.next = null;39 pre = null;40 }41 }42 }43 }

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航