1+ package PopulatingNextRightPointersinEachNode ;
2+
3+ import commons .datastructures .TreeLinkNode ;
4+
5+ /**
6+ * User: Danyang
7+ * Date: 1/27/2015
8+ * Time: 21:49
9+ *
10+ * Given a binary tree
11+
12+ Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be
13+ set to NULL.
14+
15+ Initially, all next pointers are set to NULL.
16+
17+ Note:
18+
19+ You may only use constant extra space.
20+ You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two
21+ children).
22+ For example,
23+ Given the following perfect binary tree,
24+ 1
25+ / \
26+ 2 3
27+ / \ / \
28+ 4 5 6 7
29+ After calling your function, the tree should look like:
30+ 1 -> NULL
31+ / \
32+ 2 -> 3 -> NULL
33+ / \ / \
34+ 4->5->6->7 -> NULL
35+ */
36+ public class Solution {
37+ /**
38+ * bfs is trivial
39+ * but require constant space thus can only dfs
40+ *
41+ *
42+ * Algorithm:
43+ * Since full binary tree, it relies on parent's next
44+ *
45+ * Notice:
46+ * 1. pre-order recursive traversal can be converted to iterative
47+ * 2. keep as few iterators as possible
48+ * @param root
49+ */
50+ public void connect_recur (TreeLinkNode root ) {
51+ if (root ==null )
52+ return ;
53+ if (root .left !=null )
54+ root .left .next = root .right ;
55+ if (root .right !=null && root .next !=null )
56+ root .right .next = root .next .left ;
57+ connect_recur (root .left );
58+ connect_recur (root .right );
59+ }
60+
61+ public void connect (TreeLinkNode root ) {
62+ if (root ==null )
63+ return ;
64+ for (TreeLinkNode p =root ; p !=null ; p =p .left ) { // vertical
65+ for (TreeLinkNode cur =p ; cur !=null ; cur =cur .next ) { // horizontal
66+ if (cur .left !=null )
67+ cur .left .next = cur .right ;
68+ if (cur .right !=null && cur .next !=null )
69+ cur .right .next = cur .next .left ;
70+ }
71+ }
72+ }
73+ }
0 commit comments