嗨,你們好,我是袁小廚(由於酷愛作飯,因此本身考取了廚師證)。以前一直看你們寫的博客,學到了不少東西。而後最近萌生了本身寫的想法,將本身知道的分享給須要的同窗。之後天天會爲你們分享leetcode精選題目的各類題解和Python, JS, JQ, CSS, PHP, JAVA的一些小Demo。請你們關注我,一塊兒交流學習吧。
java
題目描述
遞歸解法
作題思路
這道題的含義意思就是將每層的節點用鏈表給鏈接起來,由於這個題目是完美二叉樹,因此咱們能夠利用遞歸,而後還能夠利用層次遍歷。遞歸算法須要注意的地方就是,咱們不能忽略了2節點的右孩子和3節點的左孩子這一條線。因此咱們須要新建一個函數來進行遞歸。
node
題目代碼
class Solution { public Node connect(Node root) { if(root==null){ return null; } //將左右孩子傳入函數中 connectTwoNode(root.left,root.right); return root; } public void connectTwoNode(Node node1, Node node2){ if(node1==null||node2==null){ return ; } node1.next = node2; //三種須要鏈接的狀況 connectTwoNode(node1.left,node1.right); connectTwoNode(node2.left,node2.right); connectTwoNode(node1.right,node2.left); } }
層次遍歷(隊列)
作題思路
關於層次遍歷的思想你們能夠參考這個文章二叉樹的層次遍歷。而後咱們能夠直接用層次遍從來作這個題及填充每一個節點的右指針2。須要注意的事咱們剛纔說的遞歸法不適用作第二題。由於每一個節點的孩子狀況可能不同。不是完美二叉樹。
算法
題目代碼
class Solution { public Node connect(Node root) { //定義一個隊列,用於層次遍歷 Queue<Node> queue = new LinkedList<Node>(); if(root == null){ return root; } queue.offer(root); while(!queue.isEmpty()){ int size = queue.size(); //建立一個指針,用於鏈接該層,注意的是,這個指針的擺放位置,每一層更新一次 Node temp = new Node(0); for(int i = 0 ; i < size ; i++){ Node q = queue.poll();//出列 temp.next = q;//指針指向該節點 temp = temp.next;//移動指針 Node left = q.left; Node right = q.right; if(left!=null){ queue.offer(left); } if(right!=null){ queue.offer(right); } } } return root; } }
BFS
作題思路
這個算法算是對剛纔算法的改進,速度更快,內存更小。主要思想就是設置一個啞結點temp,遊離在樹以外,temp.next指向該層的頭結點。而後一層一層的添加,用一個cur節點進行,定位,而後將其子節點鏈接起來,而後cur進行移動,再鏈接其子孩子,而後cur跳入下一層。pre的功能就是用來鏈接cur的子節點。該題思想和數組的雙重循環相似。這個題目的思想是我跟題解裏面的一個大神學習的,圖也來自與大神。你們能夠也能夠本身去看一下。BFS題解
數組
題目代碼
public Node connect(Node root) { if (root == null) return root; //用來定位層 Node cur = root; while (cur != null) { //啞結點,遊離在樹以外,用來預約位層數 Node dummy = new Node(0); //用來cur的子節點鏈接起來 Node pre = dummy; //而後開始遍歷當前層的鏈表 while (cur != null) { //左子樹鏈接 if (cur.left != null) { pre.next = cur.left; pre = pre.next; } //右子樹鏈接 if (cur.right != null) { pre.next = cur.right; pre = pre.next; } //到該層的下一個節點 cur = cur.next; } //到下一層 cur = dummy.next; } return root; }
總結
該題作法挺多,學會這幾種方法,能夠對作其餘題有很大幫助。目前作樹的題目能夠有本身的想法。但願和你們共同進步,對你們有幫助的話就點贊關注吧,天天都會更新哦。做者:LeetCode
連接:https://leetcode-cn.com/problems/rotate-array/solution/xuan-zhuan-shu-zu-by-leetcode/
來源:力扣(LeetCode)
著做權歸做者全部。商業轉載請聯繫做者得到受權,非商業轉載請註明出處。
函數