您的位置:首页 > 其它

Binary Tree To Double LinkedList

2013-11-14 00:02 411 查看
Change a binary tree to a double linkedlist.

class Node{
Node left;
Node right;
int val;
}

//Time complexity: O(n^2).
public Node convert(Node root) {
if(root == null) return null;

Node left = convert(root.left);
Node right = convert(root.right);

if(left != null) {
merge(getEnd(left), root);
}

if(right != null) {
merge(root, getEnd(right));
}

return (left == null) ? root : left;
}

public Node getEnd(Node root) {
Node move = root;
if(move == null) return null;
while(move.right != null) {
move = move.right;
}
return move;
}

public void merge(Node left, Node right) {
left.right = right;
right.left = left;
}

//use the circular double linkedlist
//it will use only O(n) time complexity.
public Node convert(Node root) {
if(root == null) return;
Node result = help(root);
//cancle the link of head and tail
result.left.right = null;
result.left = null;
return result;
}

public Node help(Node root) {
if(root == null) return null;

Node left = help(root.left);
Node right = help(root.right);

if(left == null && right == null) {
root.left = root;
root.right = root;
return root;
}

//keep the end of the right
Node rightTail = (right == null) ? null : right.left;

//join left with root
if(left != null) {
merge(left.left, root); //connect the end of left with root
}else {
merge(right.left, root); //connect the end of right with root
}

//join right with right
if(right != null) {
merge(root, right); // connect root with head of right
}else {
merge(root, left); //connect root with head of left
}

//join left with right
if(left != null && right != null) {
merge(rightTail, left);
}

return (left == null) ? root : left;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: