[leetcode]: 257. Binary Tree Paths
来源:互联网 发布:玉环网络安全教育平台 编辑:程序博客网 时间:2024/05/22 05:35
1.题目
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.分析
本题考察二叉树的遍历。遍历过程中记录元素的顺序,遍历到底部叶节点则完成一条路径。
3.代码
深度优先遍历,非递归
class Solution {public: vector<string> binaryTreePaths(TreeNode* root) { vector<string> ans; if (root == NULL) return ans; stack<TreeNode*> nodes; stack<string> path; nodes.push(root); path.push(to_string(root->val)); while (!nodes.empty()) { TreeNode* node = nodes.top(); nodes.pop(); string curpath = path.top(); path.pop(); if (node->left == NULL&&node->right == NULL) ans.push_back(curpath); if (node->left) { nodes.push(node->left); path.push(curpath + "->" + to_string(node->left->val)); } if (node->right) { nodes.push(node->right); path.push(curpath + "->" + to_string(node->right->val)); } } return ans; }};
DFS,递归
void getTreePath(TreeNode* root,string curPath, vector<string>& ans) { if (root->left == NULL && root->right == NULL) ans.push_back(curPath); if (root -> left) getTreePath(root->left, curPath + "->" + to_string(root->left->val), ans); if (root->right) getTreePath(root->right, curPath + "->" + to_string(root->right->val), ans);}vector<string> binaryTreePaths(TreeNode* root) { vector<string> ans; if (root == NULL) return ans; getTreePath(root, to_string(root->val), ans); return ans;}
阅读全文
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
- Windows下的Rime輸入法與小鶴雙拼的配置
- 463. Island Perimeter
- yolo
- LeetCode之Largest Number
- 【opencv】目标识别——HSV颜色识别
- [leetcode]: 257. Binary Tree Paths
- 问题分享:Greenplum Compression failed: insufficient memory
- 坚持#第182天~熟能生巧
- IMWeb提升营Day3 | 训练题14:链表中倒数第K个节点
- STL-Vector内存机制
- Visual SLAM梳理
- C++优先队列解决哈夫曼(Huffmam)编码问题 (STL priority_queue)
- Codeforces Round #416 (Div. 2) (based on MSPU Olympiad 2017)
- Vijos P1002 过河