Insertion Sort List and Binary Tree Paths
2017-04-13 12:47
381 查看
题意如下:
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中:
齐活了,完成。
再来看看链表的,insertion sort List.很明白,用插入算法来排序
没什么可讲的直接上代码:
齐活了。
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); traver 4000 se(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; } };
齐活了。
相关文章推荐
- CodeForces 750G. New Year and Binary Tree Paths
- 109. Convert Sorted List to Binary Search Tree (List; Divide-and-Conquer, dfs)
- Minimum Depth of Binary Tree and quick sort
- Balanced Binary Tree and Remove Nth Node From End List
- [CF750G]New Year and Binary Tree Paths
- Medium: Binary Tree Paths Add to List
- [CodeForces750G]New Year and Binary Tree Paths
- Binary Search , Random Seed and Binary Sort Tree
- Serialize And Deserialize Binary Tree
- 折半插入排序(binary insertion sort)源代码,运行通过
- 折半插入排序(binary insertion sort)源代码,运行通过
- AIZU 1001 Binary Tree Intersection And Union
- Binary Heap and HeapSort Review
- HBST = Hash-BinarySortTree
- ALV Tree Demo using RS_TREE_LIST_DISPLAY and RS_TREE_CONSTRUCT
- Insertion sort and Merge sort
- BinaryTreeConvertToDoubleList____<1>
- Convert Binary Search Tree to an Ordered Double Linked List
- sort list and dict
- 【数据结构与算法基础】单链表及其应用基数排序 / Singly Linked List and radix sort