LeetCode Binary Tree Right Side View

199. 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.

Example:

Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---

给定一棵二叉树,问从树的右边往左看,从上往下,看到的数组是什么。很有意思哈,一棵树变着花样出题。
想到的话,其实很简单,从右边看到的数是每一层最右边的数(好像是废话),所以我们可以对树层次遍历,取出每层最右边的数,构成的数组就是答案。完整代码如下:

class Solution {
public:
    vector<int> rightSideView(TreeNode* root)
    {
        vector<int> ans;
        if (root == NULL)
            return ans;
        queue<TreeNode*> q;
        q.push(root);
        while (!q.empty()) {
            ans.push_back(q.back()->val);
            int n = q.size();
            for (int i = 0; i < n; ++i) {
                TreeNode* tmp = q.front();
                q.pop();
                if (tmp->left)
                    q.push(tmp->left);
                if (tmp->right)
                    q.push(tmp->right);
            }
        }
        return ans;
    }
};

本代码提交AC,用时3MS。

Leave a Reply

Your email address will not be published. Required fields are marked *