关键点:
一、使用队列 T = O(N) S = O(N)
- 按照二叉树中序遍历的顺序,将每个节点放在队列中
- 从队列中依次弹出节点,并按照弹出的顺序依次连接节点
代码:
public static Node convert(Node root) {
Queue<Node> q = new LinkedList<Node>();
InOrderToQueue(q,root);
if(q.isEmpty()) {
return root;
}
Node head = q.poll();
Node pre = head;
Node cur = null;
while(!q.isEmpty()) {
cur = q.poll();
pre.right = cur;
cur.left = pre;
pre = cur;
}
pre.right = null;
return head;
}
public static void InOrderToQueue(Queue<Node> q, Node root) {
if(root == null) return;
InOrderToQueue(q,root.left);
q.offer(root);
InOrderToQueue(q,root.right);
}