Friday, February 28, 2020

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

/**
 * Definition for a binary tree node.
 * 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> ans;
        queue<TreeNode *> q;
        if (root == NULL) {
            return ans;
        }
        q.push(root);
        while (!q.empty()) {
            int size = q.size();
            for (int i = 0; i < size; i++) {
                TreeNode *node = q.front(); q.pop();
                if (i == size - 1) {
                    ans.push_back(node -> val);
                }
                if (node -> left) {
                    q.push(node -> left);
                }
                if (node -> right) {
                    q.push(node -> right);
                }
            }
        }
        return ans;
    }
};

========== Recursive =========
class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        vector<int> ans;
        unordered_set<int> st;
        helper(root, st, ans, 0);
        return ans;
    }
    
    void helper(TreeNode* root, unordered_set<int>& st, vector<int>& ans, int height) {
        if (root == NULL) {
            return;
        }
        if (st.count(height) == 0) {
            ans.push_back(root -> val);
        }
        st.insert(height);
        helper(root -> right, st, ans, height + 1);
        helper(root -> left, st, ans, height + 1);
    }
};

No comments:

Post a Comment