Leetcode: Binary Tree Right Side View

来源:互联网 发布:苹果7移动网络连接不上 编辑:程序博客网 时间:2024/04/28 13:02


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

最直观的,按层次遍历,属于BFS。

/** * 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> result;        if (root == nullptr) {            return result;        }                queue<TreeNode*> nodes;        nodes.push(root);        nodes.push(nullptr);        while (!nodes.empty()) {            TreeNode* cur = nodes.front();            nodes.pop();            if (cur->left != nullptr) {                nodes.push(cur->left);            }            if (cur->right != nullptr) {                nodes.push(cur->right);            }                        if (nodes.front() == nullptr) {                result.push_back(cur->val);                nodes.pop();                if (!nodes.empty()) {                    nodes.push(nullptr);                }            }        }                return result;    }};

DFS也可以,更简洁一些,先检查右边,再左边。

/** * 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> result;        rightSideViewUtil(root, result, 0);                return result;    }        void rightSideViewUtil(TreeNode* root, vector<int>& result, int depth) {        if (root == nullptr) {            return;        }                if (depth == result.size()) {            result.push_back(root->val);        }        rightSideViewUtil(root->right, result, depth + 1);        rightSideViewUtil(root->left, result, depth + 1);    }};


0 0