<LeetCode OJ> 257. Binary Tree Paths
来源:互联网 发布:淘宝司法拍卖网房产 编辑:程序博客网 时间:2024/05/23 19:36
Total Accepted: 29282 Total Submissions: 113527 Difficulty: Easy
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 getDfsPaths(vector<string>& result, TreeNode* node, string strpath) { if(!node->left && !node->right){//叶子 result.push_back(strpath); return ; } if(node->left) getDfsPaths(result, node->left, strpath+"->"+to_string(node->left->val)); if(node->right) getDfsPaths(result, node->right, strpath+"->"+to_string(node->right->val)); } vector<string> binaryTreePaths(TreeNode* root) { vector<string> ret; if(!root) return ret; getDfsPaths(ret, root, to_string(root->val)); return ret; }};
小结:
1,深度搜索应该立刻条件反射,采用前序式遍历(如果用递归的话)
2,深度优先搜索应该立刻联想到栈来实现迭代
3,递归具有保存变量信息的功能,有时候值得利用
联动第二十二题
【1】 22. Generate Parentheses,http://blog.csdn.net/ebowtang/article/details/50557414
注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!
原文地址:http://blog.csdn.net/ebowtang/article/details/50493936
原作者博客:http://blog.csdn.net/ebowtang
1 0
- <LeetCode OJ> 257. Binary Tree Paths
- LeetCode OJ -- Binary Tree Paths
- LeetCode OJ Binary Tree Paths
- [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
- 292. Nim Game
- SSH框架
- JDK安装不成功
- OpenCV 3.1.0 配置教程 Win7+ VS2012 / Win10 + VS2015
- HPU:1232畅通工程(并查集)
- <LeetCode OJ> 257. Binary Tree Paths
- [leetcode oj 191]Number of 1 Bits
- 等待队列 赏析
- 从 MongoDB 及 Mysql 谈B/B+树
- OpenGL系统设计——求帧速度
- C#中HttpWebRequest用Post提交Content-Type: multipart/form-data;
- 有关vs2010 QT5的环境配置
- 创建带子菜单的选项菜单
- 【每周一文】Natural Language Processing (almost) From Scratch