首页 > 代码库 > Leetcode: Populating Next Right Pointers in Each Node

Leetcode: Populating Next Right Pointers in Each Node

Given a binary tree    struct TreeLinkNode {      TreeLinkNode *left;      TreeLinkNode *right;      TreeLinkNode *next;    }Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.Initially, all next pointers are set to NULL.Note:You may only use constant extra space.You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).For example,Given the following perfect binary tree,         1       /        2    3     / \  /     4  5  6  7After calling your function, the tree should look like:         1 -> NULL       /        2 -> 3 -> NULL     / \  /     4->5->6->7 -> NULL

难度:86,与Binary Tree Level Order Traversal问题类似,把每一层的节点连成一个链表,最后一个节点连接Null. 需要找出每一层的第一个节点,从它开始依次向后连。需要前置节点的做法,这是链表的基本操作。我这道题用了一个TreeLinkNode pre来做这个前置节点,最开始不给它赋值,遍历过程中记录上一跳节点,每次一层遍历结束也把它置为Null。以它有没有被复制来判断当前节点是否是一层的起始。

 1 /** 2  * Definition for binary tree with next pointer. 3  * public class TreeLinkNode { 4  *     int val; 5  *     TreeLinkNode left, right, next; 6  *     TreeLinkNode(int x) { val = x; } 7  * } 8  */ 9 public class Solution {10     public void connect(TreeLinkNode root) {11         if (root == null) return;12         LinkedList<TreeLinkNode> queue = new LinkedList<TreeLinkNode>();13         queue.add(root);14         int ParentNumInQ = 1;15         int ChildNumInQ = 0;16         TreeLinkNode pre = null;17         18         while (!queue.isEmpty()) {19             TreeLinkNode cur = queue.poll();20             if (pre == null) {21                 pre = cur;22             }23             else {24                 pre.next = cur;25                 pre = pre.next;26             }27             ParentNumInQ--;28             if (cur.left != null) {29                 queue.add(cur.left);30                 ChildNumInQ++;31             }32             if (cur.right != null) {33                 queue.add(cur.right);34                 ChildNumInQ++;35             }36             if (ParentNumInQ == 0) {37                 ParentNumInQ = ChildNumInQ;38                 ChildNumInQ = 0;39                 pre.next = null;40                 pre = pre.next;41             }42         }43     }44 }

 

Leetcode: Populating Next Right Pointers in Each Node