FG面經Prepare: BST to Double LinkedList

BST to double linkedlist in inorder traversal sequence
Follow Up: 若是這個BST自帶prev, next, 給一個value,插進去這個node,並補全left,right,prev,next

 

 1 class TreeNode {
 2  public int val;
 3  TreeNode left;
 4  TreeNode right;
 5 }
 6 
 7 TreeNode newRoot
 8 
 9 TreeNode tree2Dll(TreeNode root) {
10   TreeNode pre = null;
11   TreeNode newRoot = null;
12   helper(root, pre);
13   return newRoot;
14 }
15 
16 public void helper(TreeNode cur, TreeNode pre) {
17   if (cur == null) {
18     return;
19   }
20   helper(cur.left, pre);
21   cur.left = pre;
22   if (pre == null) {
23      newRoot = cur;
24   }
25   else pre.right = cur;
26   pre = cur;
27   helper(cur.right, pre, newRoot);
28 }

 

Follow up:node

第一步完成基礎上,把這個new value插入BST中,一邊插入一邊記錄沿途的大於value的root node(即走了該root node的left child),做爲inorder successor. 找到inorder successor以後,經過其prev指針找到inorder predecessor, 改指針就行了spa

相關文章
相關標籤/搜索