257. Binary Tree Paths
来源:互联网 发布:网络作答系统网站 编辑:程序博客网 时间:2024/05/16 19:29
题目
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"]分析
采用先根遍历的方法遍历二叉树,当根结点为NULL时返回为0,其余为1,当遇到叶结点时将后缀"->"删除再压入v保存为一条路径;当遇到非叶结点且其左右子树均已经遍历完毕则删除当前结点在路径中的位置返回给上层调用。
/** * 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> v; if(root==NULL) return v; string s; int l,r; s+=to_string(root->val); s+="->";//题目中要求两结点间以->连接,故遍历到当前结点时也写入后缀 l=PreOrder(root->left,s,v);//对左子树先根遍历 r=PreOrder(root->right,s,v);//对右子树先根遍历 if(l==0&&r==0)//当左右子树均为空时为叶节点,删掉多余的后缀->作为路径压入v { v.push_back(s.substr(0,s.size()-2)); } return v; } int PreOrder(TreeNode* root,string& s,vector<string>& v) { if(root==NULL) return 0; s+=to_string(root->val); s+="->"; int l,r; l=PreOrder(root->left,s,v); r=PreOrder(root->right,s,v); if(l==0&&r==0) { v.push_back(s.substr(0,s.size()-2)); } int j=s.size()-3;//j指向当前结点值的最后一位 while(s[j]!='>')//从后遍历s,直到找到前一个结点的后缀符> j--; s=s.substr(0,j+1);//截取从头到前一个结点后缀符>处的字符串为需要返回的路径 return 1; }};
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
- 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
- 模板类中重载<<和>>操作符
- OpenGL添加触控
- 2026
- 去除ios移动端alert/confirm的网址(url)
- 阳光欣晴工作期间杂记,包括xcode设置、常见bug等
- 257. Binary Tree Paths
- 100条经典C语言笔试题目(下)----待补充
- 部分Dojo常用函数简介——面向对象(OO)及包机制(package system)
- linux主机远程桌面
- Oracle查询 行列式转换
- SSH:Server Apache Tomcat atlocalhost failed to start
- intValue()的用法
- 为什么反射机制要依赖类的无参构造方法
- 求n个整数中第二小的数。 相同的整数看成一个数。比如,有5个数分别是1,1,3,4,5,那么第二小的数就是3。