Insertion Sort List and Binary Tree Paths
来源:互联网 发布:兰州网络教育学生平台 编辑:程序博客网 时间:2024/06/05 15: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”],
返回所有的从叶子节点到根节点的路径,这个用递归法,一层层的遍历即可,遍历过程中非空即存入对应的vector中:
class Solution {private : vector<string> res;public : vector<string> binaryTreePaths(TreeNode* root){ if(root == NULL) { ; } else if(root->left == NULL && root->right == NULL) { string temp = to_string(root->val); res.push_back(temp); } else{ if(root->left !=NULL){ traverse(root->left,to_string(root->val)); } if(root->right !=NULL){ traverse(root->right,to_string(root->val)); } } return res; }public : void traverse(TreeNode* node, string s){ if(node == NULL) return; if(node->left == NULL && node->right == NULL){ string tmp = to_string(node->val); res.push_back(s+"->"+tmp); return ; } else { if(node->left !=NULL){ string tmp1 = to_string(node->val); traverse(node->left,s+"->"+tmp1); } if(node->right !=NULL){ string tmp2 = to_string(node->val); traverse(node->right,s+"->"+tmp2); } } } };
齐活了,完成。
再来看看链表的,insertion sort List.很明白,用插入算法来排序
没什么可讲的直接上代码:
class Solution {public : ListNode* insertionSortList(ListNode* head){ if(head == NULL || head->next ==NULL) return head; ListNode* p = new ListNode(-1); p->next = head; ListNode* pre= head; ListNode* cur = pre->next; while(cur !=NULL){ if(cur->val >=pre->val){ cur = cur->next; pre = pre->next; }else{ ListNode* insertpre = p; ListNode* insertcur = p->next; while(insertcur->val < cur->val){ insertpre = insertcur; insertcur = insertcur->next; } pre->next = cur->next; cur->next = insertcur; insertpre ->next = cur; cur = pre->next; } } head = p->next; return head; } };
齐活了。
0 0
- Insertion Sort List and Binary Tree Paths
- Medium: Binary Tree Paths Add to List
- Add to List 257. Binary Tree Paths
- [CF750G]New Year and Binary Tree Paths
- Insertion Sort List | leetcode
- Leetcode: Insertion Sort List
- [LeetCode] Insertion Sort List
- Insertion Sort List
- Leetcode: Insertion Sort List
- [LeeCode] Insertion Sort List
- leetcode-Insertion Sort List
- [LeetCode]Insertion Sort List
- Insertion Sort List
- 【LeetCode】Insertion Sort List
- LeetCode | Insertion Sort List
- LeetCode - Insertion Sort List
- Insertion Sort List
- Insertion Sort List
- 【学习笔记】机器学习-K均值(k-means)
- Java之对象集合
- reverse list between m and n
- Calendar.HOUR_OF_DAY 和 Calendar.HOUR的区别
- Linux运维笔记-课后作业-软件安装
- Insertion Sort List and Binary Tree Paths
- unit11 网络管理
- Android---WebView内存泄漏解决方法
- Java多态
- Factorial Trailing Zeroes
- C#调用C++的dll文件方法
- Linux学习 十单元练习题
- JSONdemo
- java反射总结