AC

 •  18天前


#include <bits/stdc++.h>
using namespace std;

struct TreeNode {
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};


TreeNode *buildTree(const vector<int> &arr, int &id) {
	if (id >= arr.size() || arr[id] == -1) {
		id++;
		return nullptr;
	}
	TreeNode *root = new TreeNode(arr[id]);
	id++;
	root->left = buildTree(arr, id);
	root->right = buildTree(arr, id);
	return root;
}


void dfs(TreeNode *root, string path) {
	if (!root)
		return;


	if (path.empty()) {
		path = to_string(root->val);
	} else {
		path += "->" + to_string(root->val);
	}


	if (!root->left && !root->right) {
		cout << path << endl;
		return;
	}


	dfs(root->left, path);
	dfs(root->right, path);
}

int main() {
	vector<int> arr;
	int t;


	while (cin >> t) {
		arr.push_back(t);
		if (cin.get() == '\n')
			break;
	}

	int id = 0;
	TreeNode *root = buildTree(arr, id);
	dfs(root, "");

	return 0;
}


评论:

请先登录,才能进行评论