[LeetCode] 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].

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;
    }
};

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM