克隆二叉树

来源:互联网 发布:类似易企秀的软件 编辑:程序博客网 时间:2024/06/16 04:26

题目:

深度复制一个二叉树。

给定一个二叉树,返回一个他的 克隆品 。

样例

给定一个二叉树:

     1   /  \  2    3 / \4   5

返回其相同结构相同数值的克隆二叉树:

     1   /  \  2    3 / \4   5

思路:

建立一个新节点存放当前给出的节点的值,新建的左节点等于给出的左节点,新建的有节点等于给出的右节点,依次递归下去。

代码:

class Solution {
public:
    /**
     * @param root: The root of binary tree
     * @return root of new tree
     */
    TreeNode* cloneTree(TreeNode *root) {
        // Write your code here
        if(root==NULL)
        return NULL;
        TreeNode *temp=new TreeNode(root->val);
        temp->left=cloneTree(root->left);
        temp->right=cloneTree(root->right);
        return temp;
    }
};

感想:

这个题一开始不是这样写的,借鉴别人后改称这个样子的。一开始不过是因为左右节点的地方没有处理好,类推下去最后一个节点不知道去和处理。学到最大的  temp->left=cloneTree(root->left);

0 0
原创粉丝点击