Binary Tree Right Side View

来源:互联网 发布:sql安装教程 编辑:程序博客网 时间:2024/06/06 00:50
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]

思路:题目要求是求一个二叉树的右视图。给出的tags上面有两种方式,DFS,和BFS。

方法一:DFS

(1)右视图看过来一个树,每一层如果这个层次上有节点存在的话,只有一个节点是会被添加到最后的结果res中的。

(2)这样,res的大小实际行就代表了当前访问的层次。

(3)考虑修改先序遍历的算法,当节点不为NULL的时候,如果访问的层次大于等于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:    vector<int> rightSideView(TreeNode* root) {        vector<int>res;        helper(root,0,res);        return res;    }        void helper(TreeNode*root,int level,vector<int>&res)    {        if(!root)              return;        if(level>=res.size())            res.push_back(root->val);        helper(root->right,level+1,res);        helper(root->left,level+1,res);    }};
方法二:BFS

使用层次遍历的方式,每一层的最后一个元素添加到结果的数组res中返回就可以

代码如下所示:

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



0 0