题目:
Convert Binary Tree into Doubly Linked List.
Code:
class Solution{
//level-order编排doubly linked list
public void levelList(Node root){
if(root==null) return;
Queue<Node> q = new LinkedList<Node>();
q.add(root);
Node cur = null, pre = null;
while(!q.isEmpty()){
cur = q.poll();
if(cur.left != null) q.add(cur.left);
if(cur.right != null) q.add(cur.right);
cur.left = pre;
cur.right = q.peek();
pre = cur;
}
}
//以in-order的方式编排doubly linked list
public NodePair convert(Node root){
if(root==null) return null;
NodePair leftPair = convert(root.left);
NodePair rightPair = convert(root.right);
if(leftPair != null){
root.left = leftPair.tail;
leftPair.tail.right = root;
}
if(rightPair != null){
root.right = rightPair.head;
rightPair.head.left = root;
}
return new NodePair(leftPair==null?root:leftPair.head, rightPair==null?root:rightPair.tail);
}
}
class NodePair{
Node head;
Node tail;
NodePair(Node head, Node tail){
this.head = head;
this.tail = tail;
}
}
小结:
两种方式,第一种以level order遍历二叉树,用好Queue以及双指针cur和pre就行。
第二种有点难,递归,解法来自cc150第17章。这个递归和lowest common ancestor的二叉树O(n)解法有点相似之处。