LeetCode Binary Tree Right Side View 树的层次遍历

来源:互联网 发布:小马哥激活软件 编辑:程序博客网 时间:2024/06/14 10:16

思路:

每层的最后一个元素,即使用层次遍历一遍。
时间复杂度O(N),空间复杂度O(N)。N为节点个数。

/** * 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<TreeNode*> q;        q.push(root);        TreeNode *node;        while(!q.empty()) {            int size = q.size();            for(int i = 0; i < size; ++i) {                node = q.front();                q.pop();                if(node->left) {                    q.push(node->left);                }                if(node->right) {                    q.push(node->right);                }            }            ans.push_back(node->val);        }        return ans;    }};
0 0
原创粉丝点击