栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

606. 根据二叉树创建字符串C++

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

606. 根据二叉树创建字符串C++

链接:

https://leetcode.cn/problems/construct-string-from-binary-tree/

描述:


代码: 代码一:
class Solution {
public:
	string tree2str(TreeNode* root) {
		if (root == nullptr) return "";
		if (root->left == nullptr && root->right == nullptr)
			return to_string(root->val);
		if (root->right == nullptr) {
			return to_string(root->val)
				+ "(" + tree2str(root->left) + ")";
		}
		return to_string(root->val)
			+ "(" + tree2str(root->left)
			+ ")(" + tree2str(root->right)
			+ ")";
	}
};
代码二:
class Solution {
public:
	string tree2str(TreeNode* root) {
		string ret;
		if (root == nullptr) return ret;

		ret += to_string(root->val);
		if (root->left || root->right) {
			ret += "(";
			ret += tree2str(root->left);
			ret += ")";
		}

		if (root->right) {
			ret += "(";
			ret += tree2str(root->right);
			ret += ")";
		}
		return ret;
	}
};

改进:
代码二问题:拷贝次数太多

class Solution {
public:
    void _tree2str(TreeNode* root,string& ret)
    {
        if (root == nullptr) return;

		ret += to_string(root->val);
		if (root->left || root->right) {
			ret += "(";
			_tree2str(root->left,ret);
			ret += ")";
		}

		if (root->right) {
			ret += "(";
			_tree2str(root->right,ret);
			ret += ")";
		}
    }

    string tree2str(TreeNode* root) {
        string str;
        _tree2str(root,str);
       return str;
    }
};
代码分析:

采用前序遍历的方式,遍历链表
to_string 可以将数字转化为string

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/883028.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号