【leetcode刷题笔记】Populating Next Right Pointers in Each Node II

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


最开始的想法是用一个队列和一个列表。当前遍历的层的元素放在队列中,在遍历当前层的时候,把下一层元素的next指针设置好,并且把下一层的元素放在列表中。之所以要用列表,是因为当遍历一个node的孩子的时候,它在next指针下的前驱就是列表中的最后一个元素,如果用队列的话就取不出最后一个元素,所以这里要用列表。在一层遍历结束后,要把列表中的元素全部放入到队列中,开始下一层的遍历,代码如下:

 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)
12             return;
13
14         Queue<TreeLinkNode> currLevel = new LinkedList<TreeLinkNode>();
15         List<TreeLinkNode> nextLevel = new ArrayList<TreeLinkNode>();
16
17         currLevel.add(root);
18
19         while(!currLevel.isEmpty()){
20             while(!currLevel.isEmpty()){
21                 TreeLinkNode temp = currLevel.poll();
22                 if(temp.left != null){
23                     if(!nextLevel.isEmpty() && nextLevel.get(nextLevel.size()-1).next == null)
24                         nextLevel.get(nextLevel.size()-1).next = temp.left;
25                     nextLevel.add(temp.left);
26                 }
27                 if(temp.right != null){
28                     if(!nextLevel.isEmpty() && nextLevel.get(nextLevel.size()-1).next == null)
29                         nextLevel.get(nextLevel.size()-1).next = temp.right;
30                     nextLevel.add(temp.right);
31                 }
32             }
33             List<TreeLinkNode> passby = new ArrayList<TreeLinkNode>(nextLevel);
34             currLevel.addAll(passby);
35             nextLevel.clear();
36         }
37     }
38 }

但是题目中要求要常数的额外空间,上述代码居然也AC了,可见leetcode要求不是特别严格。

那么我们怎么把上述代码修改成原地算法呢?

首先,对于上述用到的列表,其实我们每次只需要列表的最后一个元素,它是当前遍历节点的孩子的前驱。如题目中所示的例子,在遍历2的右子5的时候,只要知道它的前驱是4,即刚刚遍历过的2的左子即可;同理,在遍历节点3的时候,要知道它的右孩子的前驱,只要知道刚刚遍历到的下一层节点5就可以了;所以我们只需要一个TreeNode prev记录刚刚通过父节点遍历到的下一层的节点就可以了。

其次,对于上述用到的队列,队列中元素的先后顺序其实我们在遍历上一层的时候确定这一层元素的next指针,那么在遍历这一层的时候就可以利用这个next指针了,但是仍然需要知道这一层的起点指针,这个起点指针也可以在遍历上一层的时候确定。

修改后的代码如下;

 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)
12             return;
13
14         TreeLinkNode prev = null;
15         TreeLinkNode firstNextLevel = null;
16         TreeLinkNode currNode = root;
17
18
19         while(currNode != null){
20             while(currNode != null){
21
22                 if(currNode.left != null){
23                     if(firstNextLevel == null)
24                         firstNextLevel = currNode.left;
25                     if(prev != null && prev.next == null)
26                         prev.next = currNode.left;
27                     prev = currNode.left;
28                 }
29                 if(currNode.right != null){
30                     if(firstNextLevel == null)
31                         firstNextLevel = currNode.right;
32                     if(prev != null && prev.next == null)
33                         prev.next = currNode.right;
34                     prev = currNode.right;
35                 }
36                 currNode = currNode.next;
37             }
38
39             prev = null;
40             currNode = firstNextLevel;
41             firstNextLevel = null;
42         }
43     }
44 }

【leetcode刷题笔记】Populating Next Right Pointers in Each Node II

时间: 2024-11-10 02:49:35

【leetcode刷题笔记】Populating Next Right Pointers in Each Node II的相关文章

LeetCode开心刷题五十五天——117. Populating Next Right Pointers in Each Node II

问题亟待解决: 1.一个问题一直困扰着我,想看下别人是怎么处理树的输入的,最好是以层级遍历这种清楚直观的方式. 2.关于指针*的使用 因此也导致代码不完整,没有主函数对Solution类的调用 117. Populating Next Right Pointers in Each Node II Medium 1161165FavoriteShare Given a binary tree struct Node { int val; Node *left; Node *right; Node

【leetcode刷题笔记】Sum Root to Leaf Numbers

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. An example is the root-to-leaf path 1->2->3 which represents the number 123. Find the total sum of all root-to-leaf numbers. For example, 1 / 2 3 T

【leetcode刷题笔记】Longest Consecutive Sequence

Given an unsorted array of integers, find the length of the longest consecutive elements sequence. For example,Given [100, 4, 200, 1, 3, 2],The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. Your algorithm should run in

【leetcode刷题笔记】Remove Duplicates from Sorted Array II

Follow up for "Remove Duplicates":What if duplicates are allowed at most twice? For example,Given sorted array A = [1,1,1,2,2,3], Your function should return length = 5, and A is now [1,1,2,2,3]. 题解: 设置两个变量:右边kepler和前向游标forward.如果当前kepeler所指的元素和

【leetcode刷题笔记】Restore IP Addresses

Given a string containing only digits, restore it by returning all possible valid IP address combinations. For example:Given "25525511135", return ["255.255.11.135", "255.255.111.35"]. (Order does not matter) 题解:深度优先搜索.用resul

【leetcode刷题笔记】Path Sum

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For example:Given the below binary tree and sum = 22, 5 / 4 8 / / 11 13 4 / \ 7 2 1 return true, as t

【leetcode刷题笔记】Insertion Sort List

Sort a linked list using insertion sort. 题解:实现链表的插入排序. 要注意的地方就是,处理链表插入的时候尽量往当前游标的后面插入,而不要往前面插入,后者非常麻烦.所以每次利用kepeler.next.val和head.val比较大小,而不是kepeler.val和head.val比较大小,因为如果用后者,要把head指向的节点插入到kepeler指向的节点的前面,如果kepeler指向的节点是头结点,就更麻烦了. 代码如下: 1 /** 2 * Defi

【leetcode刷题笔记】Max Points on a Line

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line. 题解: 思路比较简单,每条直线都可以表示为y=kx+b,所以对于任意三点,如果它们共线,那么它们中任意两点的斜率都相等. 所以就遍历points数组,对其中的每一个元素计算它和位于它后面的数组元素的斜率并保存在一个hashmap中. 这个hashmap的键就是两点构成直线的斜率,值就是和当前元素po

【leetcode刷题笔记】Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For example,Given n = 3, You should return the following matrix: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ] 题解:以前做过的Spiral Matrix是给一个矩阵螺旋式的输出,这道题是给一个n,螺旋式的