[LeetCode257]Binary Tree Paths
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode257]Binary Tree Paths相关的知识,希望对你有一定的参考价值。
题目:
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1 / 2 3 5
All root-to-leaf paths are:
["1->2->5", "1->3"]
求一个二叉树的所有路径
代码:
/** * Definition for a binary tree node. * struct TreeNode { * int val;( * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void RootPath(vector<string>& resultVec, TreeNode *root, string s) { if (root->left == NULL && root->right == NULL) { resultVec.push_back(s); return; } if (root->left) { RootPath(resultVec, root->left, s + "->" + to_string(root->left->val)); } if (root->right) { RootPath(resultVec, root->right, s + "->" + to_string(root->right->val)); } } vector<string> binaryTreePaths(TreeNode* root) { vector<string> result; if (root == NULL) return result; RootPath(result, root, to_string(root->val)); return result; } };
以上是关于[LeetCode257]Binary Tree Paths的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 257. Binary Tree Paths
Java [Leetcode 257]Binary Tree Paths
leetcode?python 257. Binary Tree Paths
leetcode 257. Binary Tree Paths