257、Binary Tree Paths
来源:互联网 发布:给淘宝差评怎么写 编辑:程序博客网 时间:2024/06/05 07:42
题目:
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"]
解题思路:
树的DFS遍历。
python版本:
# Definition for a binary tree node.# class TreeNode(object):# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution(object): def binaryTreePaths(self, root): """ :type root: TreeNode :rtype: List[str] """ def dfs(root,path): if(root.left==None and root.right==None): self.ans.append(path) if(root.left!=None): dfs(root.left, path+'->'+str(root.left.val)) if(root.right!=None): dfs(root.right, path+'->'+str(root.right.val)) self.ans = [] if(root!=None): dfs(root,str(root.val)) return self.ans
c++版本:
/** * 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> ans; string dfs(TreeNode* root,string path){ if(root->left==NULL and root->right==NULL) ans.push_back(path); if(root->left) dfs(root->left,path+"->"+to_string(root->left->val)); if(root->right) dfs(root->right,path+"->"+to_string(root->right->val)); } vector<string> binaryTreePaths(TreeNode* root) { if(root!=NULL) dfs(root,to_string(root->val)); return ans; }};
0 0
- 257 Binary Tree Paths
- 257 Binary Tree Paths
- 257 Binary Tree Paths
- [257]Binary Tree Paths
- 257、Binary Tree Paths
- 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
- java/TreeSet
- 搜索引擎综述
- IOS XML解析之GDataXML
- 1082. Read Number in Chinese (25)
- iOS开发之详解剪贴板
- 257、Binary Tree Paths
- SSH自动注入对象中对象为空。com.sun.jdi.InvocationException occurred invoking method
- <html5+css3+js>判断和循环
- Action/Service/DAO
- 左值和右值问题
- Maven的安装及配置
- 短信--Text与PDU
- 信号量、互斥锁,读写锁和条件变量的区别
- 设置自己喜欢的eclipse背景风格