257. Binary Tree Paths(DFS)
来源:互联网 发布:商城html源码下载 编辑:程序博客网 时间:2024/06/05 10:46
1. Description
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"]
2. Analysis
既然是二叉树,自然就会想到二叉树遍历算法,采用先序遍历的思想,从左到右遍历每个叶结点。需要注意的是,当跑到第一个叶节点,并记录第一条路径后,如何能跑到第二个叶节点,找到第二条路径,因为这条路径(String表示)的前部分是相同的,一开始我直接使用引用传参了,然而很明显这是不对的,后来改成了值引用,在递归的过程保存结果,开销大了些,结果是正确的。
3. Algorithm achievement
/** * 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: /*int 转 string*/ static string toString(const int num) { stringstream transfer; transfer << num; return transfer.str(); } static void recursizeBTP(TreeNode* root, string ans, vector<string>& res) { if(root == NULL) return; ans += toString(root->val); /*非根结点需要加连接符号—>*/ if(root->left != NULL || root->right != NULL ) ans += "->"; /*到达根结点*/ if(root->left == NULL && root->right == NULL) { res.push_back(ans); return; } recursizeBTP(root->left, ans, res); recursizeBTP(root->right, ans, res); return; } vector<string> binaryTreePaths(TreeNode* root) { if(root == NULL) return {}; vector<string> res; string ans = toString(root->val); /*整棵树只有根结点的情况*/ if(root->left == NULL && root->right == NULL ) { res.push_back(ans); return res; } /*不仅根结点,就需要加上连接符号->*/ if(root->left != NULL || root->right != NULL) ans += "->"; TreeNode * node = root; if(root->left != NULL) { recursizeBTP(root->left, ans, res); } if(root->right != NULL) { recursizeBTP(root->right, ans, res); } return res; }};
阅读全文
0 0
- 257. Binary Tree Paths(DFS)
- DFS:257. Binary Tree Paths
- leetcode 257. Binary Tree Paths(DFS)
- LeetCode257. Binary Tree Paths(dfs)
- leetcode 257. Binary Tree Paths 深度优先遍历DFS
- 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
- shiro授权
- Json
- JUPITER+PYTHON+SELENIUM(UBUNTU)
- Retrofit2+RxJava2
- TOP命令
- 257. Binary Tree Paths(DFS)
- 解决服务器80端口监听异常导致无法打开和访问网站的问题
- 云栖长卷:一张图看懂云栖七年
- 自定义闪烁Textview
- spark dataset,dataframe学习
- shiro与项目集成开发
- 一文理解深度学习,卷积神经网络,循环神经网络的脉络和原理2-卷积神经网络
- brew直接安装解压工具
- java后台调用接口并且传递相关参数