Populating Next Right Pointers in Each Node II

Posted huangyichun

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Populating Next Right Pointers in Each Node II相关的知识,希望对你有一定的参考价值。

题目:

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

  题目的大致意思是:使用O(1)的空间对树进行遍历,并且设置next指针。因此不能使用递归和队列进行广度优先搜索。
  解题思路: 采用指针,进行二叉树的广度优先搜索。总体是设置3个指针,分别为parent, pre, next。
其中parent执行当前要设置next指针的上层节点。pre指向当前要设置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 pre ;//用于设置next节点
15         TreeLinkNode next ; //标记下一行的开始节点
16         TreeLinkNode parent = root;//
17         
18          while(parent != null) {
19             pre = null;
20             next = null;
21             while(parent != null) {//对一行设置next值
22                 if (next == null) { //找到parent的下一行第一个节点
23                     next = (parent.left != null) ? parent.left : parent.right;
24                 }
25                 
26                 if (parent.left != null) { //parent存在子节点
27                     if (pre == null) {  //如果pre为空,说明parent.left为下一行的第一个节点,因此让pre指向它
28                         pre = parent.left;
29                     }else{  //pre不为空,设置pre的next指针
30                         pre.next = parent.left; 
31                         pre = pre.next;
32                     }
33                 }
34                 if (parent.right != null) {
35                     if (pre == null) {
36                         pre = parent.right;
37                     }else{
38                         pre.next = parent.right;
39                         pre = pre.next;
40                     }
41                 }
42                 
43                 parent = parent.next;//遍历parent的下一个节点
44             }
45             parent = next;//parent指向下一行的开始节点
46         }
47     }
48 }

 

 

以上是关于Populating Next Right Pointers in Each Node II的主要内容,如果未能解决你的问题,请参考以下文章

树Populating Next Right Pointers in Each Node

116. Populating Next Right Pointers in Each Node

116. Populating Next Right Pointers in Each Node

116. Populating Next Right Pointers in Each Node

116. Populating Next Right Pointers in Each Node

116. Populating Next Right Pointers in Each Node