日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【LeetCode笔记】117.填充每个节点的下一个右侧节点指针 II(二叉树、DFS)

發布時間:2024/7/23 编程问答 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【LeetCode笔记】117.填充每个节点的下一个右侧节点指针 II(二叉树、DFS) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

  • 題目描述
  • 思路 && 代碼

題目描述

  • 很煩…面試被這題干碎了,趕緊給查漏補缺一波!

思路 && 代碼

  • 主要思路:先右,再左(因為左邊依賴右邊!)
  • getNext():當前節點,無法包辦子節點的 next 了,這份責任交給當前節點的 next !當然,如果 next 不行,那么繼續遞歸傳遞責任(有點像責任鏈模式)
  • 對了,不一定得層序 BFS,因為對于當前節點來說,只要右邊已經維護了就行。
  • 其他見注釋~已經拉滿注釋了~
/* // Definition for a Node. class Node {public int val;public Node left;public Node right;public Node next;public Node() {}public Node(int _val) {val = _val;}public Node(int _val, Node _left, Node _right, Node _next) {val = _val;left = _left;right = _right;next = _next;} }; */class Solution {// 總思路:在當前層已經完善 next 的情況下,用當前層信息,對下一層進行維護public Node connect(Node root) {// Case 1:空節點if(root == null) return root;// Case 2:左右雙全:直接左指右if(root.left != null && root.right != null) {root.left.next = root.right;}// Case 3: 有左無右:靠你了,我的下一個節點!if(root.left != null && root.right == null) {root.left.next = getNext(root.next); // 傳入 root 的 next,用以獲取可行的 next}// Case 4: 有右if(root.right != null) {root.right.next = getNext(root.next); // 同 Case 3}// 先右再左:因為得先獲得右邊節點的 nextconnect(root.right);connect(root.left);return root;}// 獲取第一個節點。Node getNext(Node root) {// Case 1:為空:直接返回 nullif(root == null) return null; // Case 2:有左:返左節點if(root.left != null) return root.left;// Case 3:有右:返右節點if(root.right != null) return root.right;// Case 4:左右都沒有,但是有下一個節點:繼續遞歸查找if(root.next != null) return getNext(root.next);// Case 5:擺爛,啥都沒有:那就只能 null 了。return null;} }
  • 無注釋版,其實就 16 行解決!
class Solution {public Node connect(Node root) {if(root == null) return null;if(root.left != null && root.right != null) {root.left.next = root.right;}if(root.left != null && root.right == null) {root.left.next = getNext(root.next);}if(root.right != null) {root.right.next = getNext(root.next);}connect(root.right);connect(root.left);return root;}Node getNext(Node root) {if(root == null) return null;if(root.left != null) return root.left;if(root.right != null) return root.right;if(root.next != null) return getNext(root.next);return null;} }

總結

以上是生活随笔為你收集整理的【LeetCode笔记】117.填充每个节点的下一个右侧节点指针 II(二叉树、DFS)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。