leetcode

    xiaoxiao2021-03-25  189

    题意:

    给一个二叉树,将其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); } } } } }

    转载请注明原文地址: https://ju.6miu.com/read-1792.html

    最新回复(0)