[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);
 }

猜你喜欢

转载自blog.csdn.net/qq_41618373/article/details/83858941