[LeetCode] Binary Tree Right Side View 二叉樹的右側檢視
阿新 • • 發佈:2018-12-27
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]
Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.
這道題要求我們打印出二叉樹每一行最右邊的一個數字,實際上是求二叉樹層序遍歷的一種變形,我們只需要儲存每一層最右邊的數字即可,可以參考我之前的部落格 Binary Tree Level Order Traversal 二叉樹層序遍歷,這道題只要在之前那道題上稍加修改即可得到結果,還是需要用到資料結構佇列queue,遍歷每層的節點時,把下一層的節點都存入到queue中,每當開始新一層節點的遍歷之前,先把新一層最後一個節點值存到結果中,程式碼如下:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> rightSideView(TreeNode *root) { vector<int> res; if (!root) return res; queue<TreeNode*> q; q.push(root); while (!q.empty()) { res.push_back(q.back()->val); int size = q.size(); for (int i = 0; i < size; ++i) { TreeNode *node = q.front(); q.pop(); if (node->left) q.push(node->left); if (node->right) q.push(node->right); } } return res; } };