leetcode199 - Binary Tree Right Side View - medium
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.
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的话就是取每层最头上那个。
实现:
class Solution { 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; } };

浙公网安备 33010602011771号