【LeetCode OJ】Populating Next Right Pointers in Each Node II

来源:互联网 发布:中国网络空间安全 编辑:程序博客网 时间:2024/04/29 11:15

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

java code : use Queue
/** * 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) {        // Note: The Solution object is instantiated only once and is reused by each test case.        if(root == null)            return ;        Queue<TreeLinkNode> que = new LinkedList<TreeLinkNode>();que.add(root);que.add(null);while(true){//poll() method return the head of queue and remove it.TreeLinkNode cur = que.poll();if(que.isEmpty())break;if(cur != null){cur.next = que.peek();}else{que.add(null);continue;}if(cur.left != null)que.add(cur.left);if(cur.right != null)que.add(cur.right);}            }}




原创粉丝点击