199. Binary Tree Right Side View

来源:互联网 发布:淘宝上的天王表是正品 编辑:程序博客网 时间:2024/06/03 12:00

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


题目要求返回从右往左看一颗二叉树能看到的数,用BSF的方法,取每一层的队列的队尾元素组成答案。


代码:


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

还可以直接遍历二叉树(优先右子树),每一层肯定能看到一个数,所以如果res的元素个数比层数小就往res后添加当前节点的值。


代码:

class Solution {public:    void recursion(TreeNode *root, int level, vector<int> &res)    {        if(root==NULL) return ;        if(res.size()<level) res.push_back(root->val);        recursion(root->right, level+1, res);        recursion(root->left, level+1, res);    }    vector<int> rightSideView(TreeNode *root) {        vector<int> res;        recursion(root, 1, res);        return res;    }};



0 0