码迷,mamicode.com
首页 > 编程语言 > 详细

375. Clone Binary Tree【LintCode java】

时间:2018-07-14 14:42:00      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:inline   int   java   render   des   lint   code   链表   copy   

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

 

解题:链表复制。递归解法比较简单,代码如下:

/**
 * 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;
        }
        TreeNode new_root = new TreeNode(root.val);
        new_root.left = cloneTree(root.left);
        new_root.right = cloneTree(root.right);
        return new_root;
    }
}

 

375. Clone Binary Tree【LintCode java】

标签:inline   int   java   render   des   lint   code   链表   copy   

原文地址:https://www.cnblogs.com/phdeblog/p/9309219.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!