Wednesday, March 15, 2017

[LintCode] 375 Clone Binary Tree 解题报告

Description
For the given binary tree, return a deep copy of it.


Example
Given a binary tree:

     1
    /  \
  2    3
 / \
4   5
return the new binary tree with same structure and same value:

     1
    /  \
  2    3
 / \
4   5



思路
BFS level order遍历。维护一个HashMap对应老的node和新的node。做完新的node以后要把parent和他连起来。



Code
/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: The root of binary tree
     * @return root of new tree
     */
    public TreeNode cloneTree(TreeNode root) {
        // Write your code here
        
        if (root == null) {
            return null;
        }
        
        HashMap<TreeNode, TreeNode> map = new HashMap<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        map.put(root, new TreeNode(root.val));
        
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            if (node.left != null) {
                queue.offer(node.left);
                map.put(node.left, new TreeNode(node.left.val));
                map.get(node).left = map.get(node.left);
            }
            if (node.right != null) {
                queue.offer(node.right);
                map.put(node.right, new TreeNode(node.right.val));
                map.get(node).right = map.get(node.right);
            }
        }
        
        return map.get(root);
    }
}