Directory:
- Linked List Cycle
- Binary Tree Right Side View
Linked List Cycle return directory
Given A linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Idea: Two pointers, one pointing to the head node, the other pointing to the next node of the head node, and then the first pointer each step forward, and the second pointer each advance two steps, if two pointers can meet, then there is a ring.
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 classSolution {Ten Public: One BOOLHascycle (ListNode *head) A { - if(head = = NULL | | head->next = =NULL) - return false; theListNode *p = head->Next; - while(P! = null && P->next! = NULL && P! =head) - { -Head = head->Next; +p = p->next->Next; - } + if(p = =head) A return true; at Else - return false; - } -}; Binary Tree Right Side View return directory
Given A binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can SE E ordered from top to bottom.
For example:
Given The following binary tree,
1 <---/ 2 3 <---\ 5 4 <---
You should return [1, 3, 4] .
Idea: traverse the right side of the root node Saozi right, then the right child of the right subtree, and the children of Zuozi in the number of layers larger than the last child of the right child to save it!
1 /**2 * Definition for binary tree3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8 * };9 */Ten classSolution { One Public: Avector<int> Rightsideview (TreeNode *root) - { -vector<int>ret; the if(Root = =NULL) - returnret; -Ret.push_back (root->val); -vector<int>Retl; +vector<int>retr; -Retl = Rightsideview (root->Left ); +RETR = Rightsideview (root->Right ); A for(inti =0; I < retr.size (); ++i) at Ret.push_back (Retr[i]); - if(Retr.size () <retl.size ()) - { - for(inti = Retr.size (); I < retl.size (); ++i) - Ret.push_back (Retl[i]); - } in returnret; - } to};
Leetcode (Medium)