LeetCode No.199 Binary Tree Right Side View

来源:互联网 发布:战狼2知乎 编辑:程序博客网 时间:2024/06/04 18:46

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

====================================================================================
题目链接:https://leetcode.com/problems/binary-tree-right-side-view/

题目大意:求二叉树的右视图

思路:对二叉树进行层次遍历,每次更新,最后一个值就是该层的右视图。

附上代码:

/** * 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 ;        if ( root == NULL )            return ans ;        queue < pair <TreeNode*,int> > q ;        q.push ( make_pair ( root , 0 ) ) ;        while ( !q.empty() )        {            pair <TreeNode*,int> node = q.front() ;            q.pop() ;            TreeNode* temp = node.first ;            int index = node.second ;            if ( ans.size() <= index )                ans.push_back ( 0 ) ;            ans[index] = temp -> val ;            if ( temp -> left )                q.push ( make_pair ( temp -> left , index + 1 ) ) ;            if ( temp -> right )                q.push ( make_pair ( temp -> right , index + 1 ) ) ;        }        return ans ;    }};


0 0
原创粉丝点击