本文主要是介绍LintCode 375 深度复制一个二叉树。 给定一个二叉树,返回一个他的 克隆品 。,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
解一、返回值在return
/*** Definition of TreeNode:* class TreeNode {* public:* int val;* TreeNode *left, *right;* TreeNode(int val) {* this->val = val;* this->left = this->right = NULL;* }* }*/class Solution {
public:/*** @param root: The root of binary tree* @return: root of new tree*/TreeNode * cloneTree(TreeNode * root) {TreeNode *roota;roota=dfs(root);return roota;}TreeNode * dfs(TreeNode * root){if(root==NULL) return NULL;TreeNode * ans;ans=new TreeNode(root->val);if(root->left!=NULL){ans->left=dfs(root->left);}if(root->right!=NULL){ans->right=dfs(root->right);}return ans;}
};
解二、返回值在参数表里,用&
/*** Definition of TreeNode:* class TreeNode {* public:* int val;* TreeNode *left, *right;* TreeNode(int val) {* this->val = val;* this->left = this->right = NULL;* }* }*/class Solution {
public:/*** @param root: The root of binary tree* @return: root of new tree*/TreeNode * cloneTree(TreeNode * root) {TreeNode *roota;dfs(root,roota);return roota;}void dfs(TreeNode * root,TreeNode * &roota){if(root==NULL) {roota=NULL;return;}roota=new TreeNode(root->val);if(root->left!=NULL){dfs(root->left,roota->left);}if(root->right!=NULL){dfs(root->right,roota->right);}}
};
这篇关于LintCode 375 深度复制一个二叉树。 给定一个二叉树,返回一个他的 克隆品 。的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!