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.

题目来自leetcode

分析:

目前的解法是O(n)的levelorder traversal,不知道有没有更快的方法。

解法:

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

results matching ""

    No results matching ""