1+ H
2+
3+ 非perfect tree , 也就是有random的null children . DFS +BFS
4+
5+
6+ Populating Next Right Pointers in Each Node I 里面依赖parent .next .left来作链接 ,但现在这个parent .next .left很可能也是Null .
7+
8+ 1. 于是需要移动parent去找children level的next node 。
9+ 2. 并且每次在一个level , 要用BFS的思想把所有parent 过一遍 ,也就是把parent 正下方的children全部用 .next链接起来
10+ 原因 : 到下一层children变成parent , 他们需要彼此之间的connection , grand children才可以相互连接 。
11+
12+
13+ Note : runtime O (n * 2 ^log (n ) ) = O (n ^2 ), not good .
14+
15+ ```
16+ /*
17+ Follow up for problem "Populating Next Right Pointers in Each Node".
18+
19+ What if the given tree could be any binary tree? Would your previous solution still work?
20+
21+ Note:
22+
23+ You may only use constant extra space.
24+ For example,
25+ Given the following binary tree,
26+ 1
27+ / \
28+ 2 3
29+ / \ \
30+ 4 5 7
31+ After calling your function, the tree should look like:
32+ 1 -> NULL
33+ / \
34+ 2 -> 3 -> NULL
35+ / \ \
36+ 4-> 5 -> 7 -> NULL
37+ Hide Company Tags Microsoft Bloomberg Facebook
38+ Hide Tags Tree Depth-first Search
39+ Hide Similar Problems (M) Populating Next Right Pointers in Each Node
40+
41+ */
42+
43+ /**
44+ * Definition for binary tree with next pointer.
45+ * public class TreeLinkNode {
46+ * int val;
47+ * TreeLinkNode left, right, next;
48+ * TreeLinkNode(int x) { val = x; }
49+ * }
50+ */
51+
52+ /*
53+ DFS to traverse the tree.
54+ Also BFS using next pointer. clear node's children level per visit
55+ */
56+ public class Solution {
57+ public void connect (TreeLinkNode root ) {
58+ if (root == null || (root .left == null && root .right == null )) {
59+ return ;
60+ }
61+ dfs (root );
62+ }
63+ //Clear connection problems on each level: because the lower children level will relay on parent's level connection.
64+ public void dfs (TreeLinkNode node ) {
65+ if (node == null ) {
66+ return ;
67+ }
68+ TreeLinkNode parent = node ;
69+ while (parent != null ) {
70+ //Connect left-> right in normal case
71+ if (parent .left != null ) {
72+ parent .left .next = parent .right ;
73+ }
74+ //Left || right: one of needs to use addRight(node) method to build the .next bridge.
75+ if (parent .left != null && parent .left .next == null ) {//Fact: parent.right = null, from last step
76+ parent .left .next = addRight (parent );
77+ } else if (parent .right != null && parent .right .next == null ) {
78+ parent .right .next = addRight (parent );
79+ }
80+ parent = parent .next ;
81+ }
82+
83+ dfs (node .left );
84+ dfs (node .right );
85+ }
86+
87+ //Always take parentNode, and try to return the very first available node at child level
88+ public TreeLinkNode addRight (TreeLinkNode node ) {
89+ while (node != null ) {
90+ if (node .next == null ) {
91+ return null ;
92+ }
93+ if (node .next .left != null ) {
94+ return node .next .left ;
95+ }
96+ if (node .next .right != null ) {
97+ return node .next .right ;
98+ }
99+ node = node .next ;
100+ }
101+ return null ;
102+ }
103+
104+ }
105+
106+
107+ ```
0 commit comments