比较tricky的解法,不用额外的内存
首先考虑将二叉树转换成双向链表
[LeetCode] 426. Convert Binary Search Tree to Sorted Doubly Linked List
将二叉搜索树转为有序双向链表
然后通过查找链表中间节点的方法找到中位数
def doubleconvert(root):
if not root:
return None
def inorder(root,pre,head):
# pre, mark the previous node
# head, help find the head node
if not root:
return
inorder(root.left,pre,head)
if not head:
head=root
pre=root
else:
#pre.left=root
#root.right=pre
#fix a bug:
pre.right=root
root.left=pre
pre=root
inorder(root.right,pre,head)
pre=None
head=None
inorder(root,pre,head)
#come here, the head must be marked
pre.left=head
head.right=pre
return head