leetcode199 - Binary Tree Right Side View - medium
阿新 • • 發佈:2020-10-25
Given a binary tree, imagine yourself standing on therightside of it, return the values of the nodes you can see ordered from top to bottom.
Example:
Input:[1,2,3,null,5,null,4] Output:[1, 3, 4] Explanation: 1 <--- / \ 2 3 <--- \ \ 5 4 <---就是level order traversal, 每層取尾端那個node。同理left view的話就是取每層最頭上那個。 實現:
classSolution { public: vector<int> rightSideView(TreeNode* root) { vector<int> res; if (!root) return res; queue<TreeNode*> q; q.push(root); while (!q.empty()){ int n = q.size(); TreeNode* cur;while (n){ cur = q.front(); q.pop(); if(cur->left) q.push(cur->left); if(cur->right) q.push(cur->right); n--; } res.push_back(cur->val); }return res; } };