题目:二叉树右侧视图
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]
.
题意:
给定一棵二叉树,想象你自己站在该二叉树的右侧,按照从根节点到底端叶子节点的顺序返回你可以看到的节点的值。
思路一:
BFS实现,这道题要求我们打印出二叉树每一行最右边的一个数字,实际上是求二叉树层序遍历的一种变形,我们只需要保存每一层最右边的数字即可。还是需要用到数据结构队列queue,遍历每层的节点时,把下一层的节点都存入到queue中,每当开始新一层节点的遍历之前,先把新一层最后一个节点值存到结果中。
代码:C++版:4ms
/** * 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; if (!root) return res; queue<TreeNode*> q; q.push(root); while (!q.empty()) { res.push_back(q.back()->val); int size = q.size(); for (int i=0; i<size; ++i) { TreeNode *node = q.front(); q.pop(); if (node->left) q.push(node->left); if (node->right) q.push(node->right); } } return res; } };
思路二:
DFS实现,依次递归左右子树,将每一层的最右端节点保存进vector数组中,完成整个二叉树的遍历。
代码:C++版:4ms
/** * 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> right; if (!root) return right; rightView(root, right, 0); return right; } void rightView(TreeNode *node, vector<int> &right, int level) { if (!node) return ; if (level == right.size()) right.push_back(node->val); rightView(node->right, right, level + 1); rightView(node->left, right, level + 1); } };