LeetCode(Medium)

來源:互聯網
上載者:User

標籤:

目錄:

  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         else24             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)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.