Title Description
Enter a binary search tree, the binary search tree converted into a doubly linked list sorted. Requirements can not create any new node, point to only adjust the tree node pointer.
examples:
solution:
Because it is a binary search tree, so in order to traverse the result is sorted.
Inorder traversal achieved by using a stack. When traversing, right after a point before a junction node, a rear left node point before a junction point. (10 connects the left subtree of the maximum value, the minimum simultaneous connections right subtree.)
public TreeNode convert(TreeNode root){ if(root==null){ return null; } Stack<TreeNode> stack = new Stack<>(); TreeNode cur = root; TreeNode res = null; TreeNode pre = null; while(cur != null || !stack.isEmpty()){ if(cur != null){ stack.push(cur); cur = cur.left; }else{ cur = stack.pop(); if(pre == null){ pre = cur; res = pre; }else{ pre.right = cur; cur.left = pre; pre = cur; } cur = cur.right; } } return res;
}
It can be converted to recursively