给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
示例:
输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:
1 <---
/
2 3 <---
5 4 <---
code:bfs
/** * 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) { if(root==nullptr) return {}; vector<int> res; queue<TreeNode*> q; q.push(root); TreeNode* last=root,*nlast=nullptr; while(!q.empty()) { root=q.front(); q.pop(); if(root->left) { q.push(root->left); nlast=root->left; } if(root->right) { q.push(root->right); nlast=root->right; } if(root==last) { res.push_back(root->val); last=nlast; } } return res; } };
code:递归,根,右,左,当当前深度比最大深度大时,放入结果集
/** * 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 { private: void rightSideViewCore(TreeNode* root,vector<int>& res,int deep,int& maxDeep) { if(root==nullptr) return ; if(deep>maxDeep) { maxDeep=deep; res.push_back(root->val); } rightSideViewCore(root->right,res,deep+1,maxDeep); rightSideViewCore(root->left,res,deep+1,maxDeep); } public: vector<int> rightSideView(TreeNode* root) { if(root==nullptr) return {}; vector<int> res; int maxDeep=0; rightSideViewCore(root,res,1,maxDeep); return res; } };