LeetCode OJ 之 Binary Tree Paths(二叉树路径)
来源:互联网 发布:ae软件破解版 编辑:程序博客网 时间:2024/06/05 16:44
题目:
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"]
思路:
前序递归即可。
代码1:
/** * 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> result; if(root == NULL) return result; string path; binaryTreePaths(root , result , path); return result; } void binaryTreePaths(TreeNode* root , vector<string> &result , string path) { if(root == NULL) return; if(path.empty()) path += to_string(root->val); else { path += "->"; path += to_string(root->val); } if(root->left == NULL && root->right == NULL) { result.push_back(path); return; } binaryTreePaths(root->left , result , path); binaryTreePaths(root->right , result , path); }};
代码2:
/** * 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> result; if(root == NULL) return result; string path; binaryTreePaths(root , result , path); return result; } void binaryTreePaths(TreeNode* root , vector<string> &result , string path) { if(root == NULL) return; if(root->left == NULL && root->right == NULL) { result.push_back(path + to_string(root->val)); return; } binaryTreePaths(root->left , result , path + to_string(root->val) + "->"); binaryTreePaths(root->right , result , path + to_string(root->val) + "->"); }};
0 0
- LeetCode OJ 之 Binary Tree Paths(二叉树路径)
- 【Leetcode】257 Binary Tree Paths 二叉树的路径
- leetcode解题之57. Binary Tree Paths&129. Sum Root to Leaf Numbers Java版 (二叉树路径)
- LeetCode OJ 之 Invert Binary Tree(反转二叉树)
- Binary Tree Paths (二叉树路径遍历)
- Binary Tree Paths(二叉树的路径)
- 257. Binary Tree Paths(打印二叉树所有路径)
- LeetCode OJ -- Binary Tree Paths
- LeetCode OJ Binary Tree Paths
- LeetCode 257 Bianry Tree Paths(二叉树路径保存)
- 257.leetcode Binary Tree Paths(easy)[二叉树深度路径遍历]
- Tree----- 257. Binary Tree Paths(二叉树从根节点开始的所有路径)
- lintcode binary-tree-paths 二叉树的所有路径
- 257. Binary Tree Paths 二叉树的路径
- 257. Binary Tree Paths | 二叉树的路径
- 257. Binary Tree Paths打印二叉树路径
- LeetCode 之 Binary Tree Paths
- leetcode之Binary Tree Paths
- 数据库查询显示问题
- 安卓文件安全删除问题 --- java.io.IOException: open failed: EBUSY (Device or resource busy) (System.err)
- SpringMVC源码剖析(二)- DispatcherServlet的前世今生
- 用Python的requests库作接口测试——上传文件
- Git远程仓库学习笔记
- LeetCode OJ 之 Binary Tree Paths(二叉树路径)
- Sublime Text 3 支持的热门插件推荐
- OC之继承
- Java构造和解析Json数据的两种方法详解一
- Command Injection Flaws Attack(WebGoat5.4)
- 获取系统内存显示程序
- SpringMVC源码剖析(三)- DispatcherServlet的初始化流
- Eclipse工具使用技巧总结
- 2、 微控制器选择