您的位置:首页 > 其它

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中:

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;
}

};


齐活了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: