Populating Next Right Pointers in Each Node II

Follow up for problem "Populating Next Right Pointers in Each Node".

What if the given tree could be any binary tree? Would your previous solution still work?

Note:

  • You may only use constant extra space.

For example,
Given the following binary tree,

         1
       /  \
      2    3
     / \    \
    4   5    7

After calling your function, the tree should look like:

         1 -> NULL
       /  \
      2 -> 3 -> NULL
     / \    \
    4-> 5 -> 7 -> NULL
與Populating Next Right Pointers in Each Node 基本一致  只是在向隊列中加入子節點時要對左右節點分別判斷 代碼如下:
public class Solution {
    public void connect(TreeLinkNode root) {
        if(root==null) return ;
		int count=1;
		int level=0;
		Queue<TreeLinkNode> que =new LinkedList<TreeLinkNode>();
		que.offer(root);
		while(que.isEmpty()!=true){
			level=0;
			for(int i=0;i<count;i++){
				root=que.peek();
				que.poll();
				if(i<count-1){
				    root.next=que.peek();
				}else{
				    root.next=null;
				}
				if(root.left!=null){
					que.offer(root.left);
					level++;
				}
				if(root.right!=null){
				    que.offer(root.right);
					level++;
				}
			}
			count=level;
		}
    }
}
要求空間負載度爲常數  所以上方法不滿足要求 與I一樣 對上一層節點的next處理完後再處理下一層節點 只是考慮下層節點時 要分別考慮其左右子節點的空否狀態 PS:進行遞歸時 要先右再左 右邊節點完成後才能使得左邊的next節點得到完善 代碼如下:
<pre name="code" class="java">public class Solution {
    public void connect(TreeLinkNode root) {
        if(root==null)return ;
        if(root.left!=null){
            if(root.right!=null){
                root.left.next=root.right;
            }else{
                TreeLinkNode p=root.next;
                while(p!=null){
                    if(p.left!=null){
                        root.left.next=p.left;
                        break;
                    }
                    if(p.right!=null){
                        root.left.next=p.right;
                        break;
                    }
                    p=p.next;
                }
            }
        }
        if(root.right!=null){
                TreeLinkNode p=root.next;
                while(p!=null){
                    if(p.left!=null){
                        root.right.next=p.left;
                        break;
                    }
                    if(p.right!=null){
                        root.right.next=p.right;
                        break;
                    }
                    p=p.next;
                }
        }
        
        connect(root.right);
        connect(root.left);
    }
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章