1. 程式人生 > >[leetcode]populating-next-right-pointers-in-each-node

[leetcode]populating-next-right-pointers-in-each-node

1.populating-next-right-pointers-in-each-node

問題描述:
Given a binary tree

struct TreeLinkNode {
  TreeLinkNode *left;
  TreeLinkNode *right;
  TreeLinkNode *next;
}

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL.

Note:
You may only use constant extra space.
You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).

For example,
Given the following perfect binary tree,
         1
       /  \
      2    3
     / \  / \
    4  5  6  7

After calling your function, the tree should look like:
         1 -> NULL
       /  \
      2 -> 3 -> NULL
     / \  / \
    4->5->6->7 -> NULL

思路:
由於是完全二叉樹,即一個節點的若有左孩子一定有右孩子,所以左孩子的next應該指向同父節點的右孩子。而右孩子的next應該指向其父節點next的左孩子(在其父節點的next不為空的情況下),若父節點的next為空,則右孩子的next也為空。遍歷到某一節點的操作是:為其孩子節點新增正確的next,所以應記錄下當且節點的next,供其右孩子新增next。再遞迴去遍歷其左孩子和右孩子。

程式碼:

public class Solution {
    public void connect(TreeLinkNode root) {
        if(root==null){
            return;
        }
        TreeLinkNode p=root.next;
        if(root.left!=null){
            root.left.next=root.right;
            if(p!=null){
                root.right.next=p.left;
            }
            else{
                root.right.next=p;
            }
        }
        connect(root.left);
        connect(root.right);
    }
}

2.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

思路:
與上面不同的是此時的樹不一定是完全二叉樹,因此左孩子的next不能簡單的指向同一父節點的右孩子,因為該父節點可能沒有右孩子。分層遍歷,在遍歷到第i行時,所作的操作是為第i+1行的節點新增正確的next指標。因此我們需要兩個指標,一個是用於遍歷第i行節點的cur指標,一個是用於新增第i+1行next的prev指標。先new一個head指標,其next應指向第i+1行的第一個節點,用於遞迴使用。i+1行遍歷時,prev指標同連結串列一樣,新增好next指標後,便指向next節點,再去新增next指標。遍歷第i行時,每遍歷到一個節點,則判斷一下其左孩子/右孩子是否為空,若不為空,第i+1行prev的next便指向非空的左孩子/右孩子。接下來遞迴遍歷第i+1行。

程式碼:

public class Solution {
    public void connect(TreeLinkNode root) {
        if(root==null){
            return;
        }
        TreeLinkNode line=new TreeLinkNode(0);
        TreeLinkNode cur,prev=line;
        for(cur=root;cur!=null;cur=cur.next){
            if(cur.left!=null){
                prev.next=cur.left;
                prev=prev.next;
            }
            if(cur.right!=null){
                prev.next=cur.right;
                prev=prev.next;
            }
        }
        connect(line.next);
 }