199. Binary Tree Right Side View(BFS)

来源:互联网 发布:退火算法 matlab 编辑:程序博客网 时间:2024/06/06 18:53

1. Description

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


2.Code

  • 普通版
/** * 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) {        if(root== NULL) return {};        vector<int> res;        TreeNode* node = NULL;        queue<TreeNode*> tmp;        tmp.push(root);        //res.push_back(root->val);        while(!tmp.empty()) {            res.push_back(tmp.back()->val);            for(int i = 0, n = tmp.size(); i < n; i++) {                node = tmp.front();                tmp.pop();                if(node->left != NULL) {                    tmp.push(node->left);                }                if(node->right != NULL) {                    tmp.push(node->right);                }            }        }        return res;    }};
  • 优化版
/** * 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:    int maxlevel = 0;    vector<int> sln;    vector<int> rightSideView(TreeNode* root) {        if(!root)            return sln;        visit(root,1);        return sln;    }    void visit(TreeNode* node, int level)    {        if(level > maxlevel)        {            sln.push_back(node->val);            maxlevel = level;        }        if(node->right)            visit(node->right, level + 1);        if(node->left)            visit(node->left, level + 1);    }};
原创粉丝点击