FG面经Prepare: BST to Double LinkedList

时间:2022-05-07 21:37:11
BST to double linkedlist in inorder traversal sequence
Follow Up: 如果这个BST自带prev, next, 给一个value,插进去这个node,并补全left,right,prev,next
 class TreeNode {
public int val;
TreeNode left;
TreeNode right;
} TreeNode newRoot TreeNode tree2Dll(TreeNode root) {
TreeNode pre = null;
TreeNode newRoot = null;
helper(root, pre);
return newRoot;
} public void helper(TreeNode cur, TreeNode pre) {
if (cur == null) {
return;
}
helper(cur.left, pre);
cur.left = pre;
if (pre == null) {
newRoot = cur;
}
else pre.right = cur;
pre = cur;
helper(cur.right, pre, newRoot);
}

Follow up:

第一步完成基础上,把这个new value插入BST中,一边插入一边记录沿途的大于value的root node(即走了该root node的left child),作为inorder successor. 找到inorder successor之后,通过其prev指针找到inorder predecessor, 改指针就好了