116 Populating Next Right Pointers in Each Node 每个节点的右向指针

给定一个二叉树
    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

详见:https://leetcode.com/problems/populating-next-right-pointers-in-each-node/description/

Java实现:

递归实现:

/**
 * Definition for binary tree with next pointer.
 * public class TreeLinkNode {
 *     int val;
 *     TreeLinkNode left, right, next;
 *     TreeLinkNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void connect(TreeLinkNode root) {
        if(root==null){
            return;
        }
        if(root.left!=null){
            root.left.next=root.right;
        }
        if(root.right!=null){
            root.right.next=root.next!=null?root.next.left:null;
        }
        if(root.left!=null){
            connect(root.left);
        }
        if(root.right!=null){
            connect(root.right);
        }
    }
}

非递归实现:

/**
 * Definition for binary tree with next pointer.
 * public class TreeLinkNode {
 *     int val;
 *     TreeLinkNode left, right, next;
 *     TreeLinkNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void connect(TreeLinkNode root) {
        if(root==null){
            return;
        }
        LinkedList<TreeLinkNode> que=new LinkedList<TreeLinkNode>();
        que.offer(root);
        while(!que.isEmpty()){
            //记录本层节点的个数
            int size=que.size();
            for(int i=0;i<size;++i){
                TreeLinkNode cur=que.poll();
                //最后一个节点的next是null,不做处理
                if(i<size-1){
                    TreeLinkNode next=que.peek();
                    cur.next=next;
                }
                if(cur.left!=null){
                    que.offer(cur.left);
                }
                if(cur.right!=null){
                    que.offer(cur.right);
                }
            }
        }
    }
}

 

posted on 2018-04-05 11:21  lina2014  阅读(142)  评论(0编辑  收藏  举报

导航