leetcode_middle_78_117. Populating Next Right Pointers in Each Node II

来源:互联网 发布:手机自动播音软件 编辑:程序博客网 时间:2024/06/06 14:12

题意:

给一个二叉树,将其next指针设置为其水平右边相邻的那个结点,没有则设置为空



分析:

the code which i wrote for the 116 still work.

/** * 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) {         Queue<TreeLinkNode> q = new LinkedList<>();        if(root == null)            return;        q.offer(root);        while(!q.isEmpty()){            int size = q.size();            for(int i=0; i<size; i++){                TreeLinkNode node = q.poll();                if(i != size-1)                    node.next = q.peek();                if(node.left != null){                    q.offer(node.left);                }                if(node.right != null){                    q.offer(node.right);                }            }        }    }}


0 0
原创粉丝点击