首頁| 新聞| 娛樂| 游戲| 科普| 文學(xué)| 編程| 系統(tǒng)| 數(shù)據(jù)庫| 建站| 學(xué)院| 產(chǎn)品| 網(wǎng)管| 維修| 辦公| 熱點
Follow up for 在Populating Next Right Pointers in Each Node問題的基礎(chǔ)上,難度20,方法一樣。都是類似Binary Tree Level Order Traverse,都是把樹看成一個無向圖,然后用BFS的方式,需要記錄每一層的ParentNumInQueue以及ChildNumInQueue, 初始值為1和0,以后每次ParentNumInQ減至0說明這一層已經(jīng)遍歷完畢,這一層的Child數(shù)將成為下一層的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 }
在Populating Next Right Pointers in Each Node問題的基礎(chǔ)上,難度20,方法一樣。都是類似Binary Tree Level Order Traverse,都是把樹看成一個無向圖,然后用BFS的方式,需要記錄每一層的ParentNumInQueue以及ChildNumInQueue, 初始值為1和0,以后每次ParentNumInQ減至0說明這一層已經(jīng)遍歷完畢,這一層的Child數(shù)將成為下一層的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 }
索泰發(fā)布一款GTX 1070 Mini迷
AMD新旗艦顯卡輕松干翻NVIDIA
索泰發(fā)布一款GTX 1070 Mini迷你版本:小機(jī)
芭蕾舞蹈表演,真實美到極致
下午茶時間,悠然自得的休憩
充斥這繁華奢靡氣息的城市迪拜風(fēng)景圖片
從山間到田野再到大海美麗的自然風(fēng)景圖片
肉食主義者的最愛美食烤肉圖片
夏日甜心草莓美食圖片
人逢知己千杯少,喝酒搞笑圖集
搞笑試卷,學(xué)生惡搞答題
新聞熱點
疑難解答
圖片精選
使用ASP建設(shè)私人搜索引擎
華為短消息中心的發(fā)展與應(yīng)用
移動通信計費(fèi)及客戶服務(wù)系統(tǒng)
移動客戶服務(wù)中心系統(tǒng)
網(wǎng)友關(guān)注