[leetcode] 257. Binary Tree Paths
来源:互联网 发布:c语言 设备端接入 编辑:程序博客网 时间:2024/06/07 20:27
Question :
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"]
Solution :
主要要做的就是遍历一棵树,不过要记录遍历时候遇到的值,这里使用dfs来完成遍历并记录沿途的值。
/** * 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> ret; if(root == NULL) { return ret; } string root_val = to_string(root->val); dfs(ret, root, root_val); return ret; } void dfs(vector<string> & v, TreeNode* root, string str){ if(root->left == NULL && root->right == NULL){ v.push_back(str); return; } if(root->left != NULL) { string val_str = str + "->" + to_string(root->left->val); dfs(v, root->left, val_str); } if(root->right != NULL) { string val_str = str + "->" + to_string(root->right->val); dfs(v, root->right, val_str); } }};
阅读全文
0 0
- [leetcode] 257. Binary Tree Paths
- 257. Binary Tree Paths LeetCode
- 【LeetCode】257. Binary Tree Paths
- LeetCode 257. Binary Tree Paths
- LeetCode *** 257. Binary Tree Paths
- leetcode 257. Binary Tree Paths
- LeetCode 257. Binary Tree Paths
- Leetcode 257. Binary Tree Paths
- LeetCode-257.Binary Tree Paths
- 【leetcode】257. Binary Tree Paths
- [Leetcode]257. Binary Tree Paths
- LeetCode - 257. Binary Tree Paths
- LeetCode 257. Binary Tree Paths
- [leetcode] 257. Binary Tree Paths
- LeetCode 257. Binary Tree Paths
- 257.[Leetcode]Binary Tree Paths
- LeetCode 257. Binary Tree Paths
- leetcode 257. Binary Tree Paths
- 翻转单词顺序列java实现
- Hibernate原理及工作流程
- chmod g+s 、chmod o+t 、chmod u+s详细说明
- 数据库中事务、存储过程、函数、同义词的使用
- javascript线程解释(setTimeout,setInterval你不知道的事)
- [leetcode] 257. Binary Tree Paths
- 满二叉树思想的应用------小猴子下落
- fstab文件详解
- Read Number in Chinese (25)
- linux下文件权限
- HDFS Ozone整体概述
- Linux不重启识别新添加的磁盘
- CA和证书
- CCF CSP 2015年03月第4题 网络延迟(求树的直径)