美文网首页我爱编程
117. Populating Next Right Point

117. Populating Next Right Point

作者: 衣介书生 | 来源:发表于2018-04-05 16:41 被阅读10次

    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
    

    这道题目可以将两个队列结合起来进行层次遍历。

    import java.util.*;
    /**
     * 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;
            }
            Queue<TreeLinkNode> q1 = new LinkedList<>();
            Queue<TreeLinkNode> q2 = new LinkedList<>();
            q1.offer(root);
            while(!q1.isEmpty()) {
                TreeLinkNode temp = q1.poll();
                if(q1.isEmpty()) {
                    temp.next = null;
                } else {
                    temp.next = q1.peek();
                }
                if(temp.left != null) {
                    q2.offer(temp.left);
                }
                if(temp.right != null) {
                    q2.offer(temp.right);
                }
                if(q1.isEmpty() && !q2.isEmpty()) {
                    while(!q2.isEmpty()) {
                        q1.offer(q2.poll());
                    }
                }
            }
        }
    }
    

    相关文章

      网友评论

        本文标题:117. Populating Next Right Point

        本文链接:https://www.haomeiwen.com/subject/pjevcftx.html