[Leetcode][第116 117题][JAVA][填充每个节点的下一个右侧节点指针][BFS][链表前驱节点]
生活随笔
收集整理的這篇文章主要介紹了
[Leetcode][第116 117题][JAVA][填充每个节点的下一个右侧节点指针][BFS][链表前驱节点]
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【問題描述】[中等]
【解答思路】
1. BFS層次遍歷思想 (通用)
時間復雜度:O(N) 空間復雜度:O(N)
public Node connect(Node root) {if (root == null)return root;Queue<Node> queue = new LinkedList<>();queue.add(root);while (!queue.isEmpty()) {//每一層的數量int levelCount = queue.size();//前一個節點Node pre = null;for (int i = 0; i < levelCount; i++) {//出隊Node node = queue.poll();//如果pre為空就表示node節點是這一行的第一個,//沒有前一個節點指向他,否則就讓前一個節點指向他if (pre != null) {pre.next = node;}//然后再讓當前節點成為前一個節點pre = node;//左右子節點如果不為空就入隊if (node.left != null)queue.add(node.left);if (node.right != null)queue.add(node.right);}}return root;}2. 鏈表思想
117
時間復雜度:O(N) 空間復雜度:O(1)
116
時間復雜度:O(N) 空間復雜度:O(1)
public Node connect(Node root) {if (root == null)return root;//cur我們可以把它看做是每一層的鏈表Node cur = root;while (cur != null) {//遍歷當前層的時候,為了方便操作在下一//層前面添加一個啞結點(注意這里是訪問//當前層的節點,然后把下一層的節點串起來)Node dummy = new Node(0);//pre表示下一層節點的前一個節點Node pre = dummy;//然后開始遍歷當前層的鏈表//因為是完美二叉樹,如果有左子節點就一定有右子節點while (cur != null && cur.left != null) {//讓pre節點的next指向當前節點的左子節點,也就是把它串起來pre.next = cur.left;//然后再更新prepre = pre.next;//pre節點的next指向當前節點的右子節點,pre.next = cur.right;pre = pre.next;//繼續訪問這一行的下一個節點cur = cur.next;}//把下一層串聯成一個鏈表之后,讓他賦值給cur,//后續繼續循環,直到cur為空為止cur = dummy.next;}return root;}117的思路
時間復雜度:O(N) 空間復雜度:O(1)
public Node connect(Node root) {if (root == null)return null;Node pre = root;Node cur = null;while (pre.left != null) {//遍歷當前這一層的結點,然后把他們的下一層連接起來cur = pre;//cur不為空,就表示這一層還沒遍歷完,就繼續循環while (cur != null) {//讓下一層的左子節點指向右子節點cur.left.next = cur.right;//如果cur.next不為空,就表示還沒遍歷到這一層//最后的那個節點的右子節點,就讓前一個結點的右//子節點指向下一個節點的左子節點if (cur.next != null)cur.right.next = cur.next.left;//然后繼續連接下一個節點的 子節點cur = cur.next;}//繼續下一層pre = pre.left;}return root;} 作者:sdwwld 鏈接:https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/solution/bfshe-di-gui-zui-hou-liang-chong-ji-bai-liao-100-2/ 來源:力扣(LeetCode) 著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。遞歸思路
public Node connect(Node root) {dfs(root, null);return root;}private void dfs(Node curr, Node next) {if (curr == null)return;curr.next = next;dfs(curr.left, curr.right);dfs(curr.right, curr.next == null ? null : curr.next.left);}作者:sdwwld 鏈接:https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/solution/bfshe-di-gui-zui-hou-liang-chong-ji-bai-liao-100-2/【總結】
1. BFS套路 隊列
2.重新加深了對鏈表的認視 前驅節點是個好東西
3.二叉樹的遍歷有
前序遍歷
中序遍歷
后續遍歷
深度優先搜索(DFS)
寬度優先搜索(BFS)
轉載鏈接:https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node-ii/solution/bfsjie-jue-zui-hao-de-ji-bai-liao-100de-yong-hu-by/
轉載鏈接:https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/solution/bfshe-di-gui-zui-hou-liang-chong-ji-bai-liao-100-2/
總結
以上是生活随笔為你收集整理的[Leetcode][第116 117题][JAVA][填充每个节点的下一个右侧节点指针][BFS][链表前驱节点]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql-5.5.50-winx64
- 下一篇: 华北电力大学微型计算机,华北电力大学 微