標籤:
目錄:
- Linked List Cycle
- 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)