給定一個二叉樹
struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; }
填充它的每個 next 指針,讓這個指針指向其下一個右側節點。如果找不到下一個右側節點,則將 next 指針設置為 NULL
。
初始狀態下,所有 next 指針都被設置為 NULL
。
說明:
- 你只能使用額外常數空間。
- 使用遞歸解題也符合要求,本題中遞歸程序占用的棧空間不算做額外的空間復雜度。
- 你可以假設它是一個完美二叉樹(即所有葉子節點都在同一層,每個父節點都有兩個子節點)。
示例:
給定完美二叉樹,
1 / \ 2 3 / \ / \ 4 5 6 7
調用你的函數后,該完美二叉樹變為:
1 -> NULL / \ 2 -> 3 -> NULL / \ / \ 4->5->6->7 -> NULL
遞歸法:因為是完美二叉樹,如果有左子樹,一定有右子樹。我們將結點的左子樹和右子樹相連。
如果結點next不為空,那么將結點右子樹指向結點next的左子樹。
同時遞歸處理左子樹和右子樹。
public class Solution { public void connect(TreeLinkNode root) { if(root==null)return ; if(root.left!=null){ root.left.next=root.right; if(root.next!=null)root.right.next=root.next.left; } connect(root.left); connect(root.right); } }
層序遍歷法:
/* *利用層序遍歷,每一層都將指針指向他的下一個結點, *這里用size標記每一層是否遍歷完畢。 * */ public class Solution { public void connect(TreeLinkNode root) { if(root==null)return ; Queue<TreeLinkNode> q=new LinkedList(); q.add(root); while(!q.isEmpty()){ int size=q.size(); for(int i=0;i<size;i++){ TreeLinkNode temp=q.peek();q.poll(); if(i<size-1)temp.next=q.peek(); if(temp.left!=null)q.add(temp.left); if(temp.right!=null)q.add(temp.right); } } } }
最巧妙地:利用層指針和深度的指針
public class Solution { public void connect(TreeLinkNode root) { if(root==null)return ; TreeLinkNode cur=null,start=root; while(start.left!=null){ cur=start; while(cur!=null){ cur.left.next=cur.right; if(cur.next!=null)cur.right.next=cur.next.left; cur=cur.next; } start=start.left; //這個地方是left,不是next } } }