257.BinaryTreePaths
来源:互联网 发布:10天学会单片机百度云 编辑:程序博客网 时间:2024/06/16 14:12
257.BinaryTreePaths
LeetCode
题目描述
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”]
解题思路
此题的思路就是前序遍历树,记录下每一个访问过的节点,若节点为叶子节点,则把这条路径加入到vector中,然后把这个点的值删除掉,接着访问下一个节点。每次返回上一层,就需要把这一层的节点+->删除掉。
代码
/** * 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: vector<string> binaryTreePaths(TreeNode* root) { vector<string> results; if(!root) return results; string result; PreOrder(root, results, result); return results; } void PreOrder(TreeNode* root, vector<string>& results, string& result) { string::iterator it; if(!root) return; if(root->left == nullptr && root->right == nullptr) { string temp = to_string(root->val); result = result + temp; results.push_back(result); //这里容易出错,叶子节点只需要减去叶子节点的长度 it = result.end() - temp.length(); result.erase(it,result.end()); return; } string temp = to_string(root->val); result = result + temp + "->"; PreOrder(root->left, results, result); PreOrder(root->right, results, result); //如果不是叶子节点,需要减去本身的长度+"->"的length为2. it = result.end() - (temp.length() + 2); result.erase(it,result.end()); } };
0 0
- 257.BinaryTreePaths
- LeetCode257 BinaryTreePaths(打印根节点到叶子节点的左右路径) Java题解
- <LeetCode><Easy>257BinaryTreePaths (深度优先搜索)(列表深拷贝)
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 257. Binary Tree Paths
- 简析短信收发,拦截问题
- mysql给root开启远程访问权限,修改root密码
- 汉诺塔问题
- Windows程序安装包制作——EasySetup
- RSA私钥文件(PEM)解析
- 257.BinaryTreePaths
- Url解析类
- 从0开始学习 GitHub 系列之「向GitHub 提交代码」
- find
- Android开发四大组件之一广播(Broadcast)
- Apache Kafka:下一代分布式消息系统
- cocoapods
- tsql default values, check current isolation level, check db object last update time
- 阶乘的长度