码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode(Medium)

时间:2015-04-26 16:43:25      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:

目录:

  1. Linked List Cycle

  2. Binary Tree Right Side View


 

Linked List Cycle 返回目录

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

思路:两个指针,一个指向头结点,另一个指向头结点的下一个结点,然后第一个指针每次前进一步,第二个指针每次前进两步,如果两个指针能够相遇,则存在环。

 

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     bool hasCycle(ListNode *head) 
12     {
13         if(head == NULL || head->next == NULL) 
14             return false;
15         ListNode *p = head->next;
16         while(p != NULL && p->next != NULL && p != head)
17         {
18             head = head->next;
19             p = p->next->next;
20         }
21         if(p == head)
22             return true;
23         else
24             return false;
25     }
26 };

Binary Tree Right Side View  返回目录

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

For example:
Given the following binary tree,

   1            <---
 /   2     3         <---
 \       5     4       <---

 

You should return [1, 3, 4].

 思路:分别遍历根结点的左子树和右子树的右边,然后将右子树的右孩子,以及左子树的孩子中所在层数大于右子最后一个孩子所在层数的孩子保存起来即可!

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<int> rightSideView(TreeNode *root) 
13     {
14         vector<int> ret;
15         if(root == NULL) 
16             return ret;
17         ret.push_back(root->val);
18         vector<int> retl;
19         vector<int> retr;
20         retl = rightSideView(root->left);
21         retr = rightSideView(root->right);
22         for(int i = 0; i < retr.size(); ++i)
23                 ret.push_back(retr[i]);
24         if(retr.size() < retl.size())
25         {
26             for(int i = retr.size(); i < retl.size(); ++i)
27                 ret.push_back(retl[i]);
28         }
29         return ret;
30     }
31 };

 

LeetCode(Medium)

标签:

原文地址:http://www.cnblogs.com/90zeng/p/leetcode_medium.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!