LeetCode 199二叉树的右视图 题解 C/C++

主要思路

方法一:深搜
维护一个map映射,key为树的高度,value为对应层数(高度)的最右值。在维护一个结点栈和深度栈,这两个栈也是一一对应的关系,结点与他的高度。
算法主要流程就是从根节点开始搜索,每次优先访问右子树,那么这一层的最右节点就是它。若没有右子树则访问左子树,对左子树在执行上述操作。用栈模拟该过程即可,先将左子树入栈,再将右子树入栈,然后栈顶元素出栈,优先处理的就是右子树。

方法二:广搜
对二叉树进行层次遍历,从左到右,每层最后遍历的即为最右边结点,用队列实现,不断更新每一层最右结点。

using namespace std;
struct TreeNode {
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode():val(0),left(nullptr),right(nullptr){}
	TreeNode(int x):val(x),left(nullptr),right(nullptr){}
	TreeNode(int x,TreeNode *left,TreeNode *right) : val(x),left(left),right(right){}
};


//方法一:深度优先搜索
class Solution {
public:
	vector<int> rightSideView(TreeNode *root) {
		vector<int> vec;
		if(root==nullptr)return vec;
		unordered_map<int,int> dep_rightval_map;
		int max_depth = 0;//树的深度

		stack<TreeNode *> nodeStk;
		stack<int> depthStk;
		nodeStk.push(root);
		depthStk.push(1);

		while(!depthStk.empty()) {
			TreeNode *node = nodeStk.top();nodeStk.pop();
			int depth = depthStk.top();depthStk.pop();

			if(node!=nullptr) {
				max_depth = max(depth,max_depth);

				if(dep_rightval_map.find(depth)==dep_rightval_map.end()) {//该高度还没有最右值,则插入
					dep_rightval_map[depth] = node->val;
				}
				nodeStk.push(node->left);
				nodeStk.push(node->right);
				depthStk.push(depth+1);
				depthStk.push(depth+1);
			}
		}

		for(int i = 1;i<=max_depth;i++) {
			vec.push_back(dep_rightval_map[i]);
		}
		return vec;
	}


};



//广度优先搜索
class Solution {
public:
	vector<int> rightSideView(TreeNode *root) {
		vector<int> vec;
		if(root==nullptr)return vec;
		unordered_map<int,int> dep_rightval_map;
		int max_depth = 0;//树的深度

		queue<TreeNode *> node_que;
		queue<int> depth_que;
		node_que.push(root);
		depth_que.push(1);

		while(!node_que.empty()) {
			TreeNode *node = node_que.front();node_que.pop();
			int depth = depth_que.front();depth_que.pop();

			if(node!=nullptr) {
				max_depth = max(depth,max_depth);

				//不需要判断,因为是层次遍历,每一层最后一个结点,不断更新即可
				dep_rightval_map[depth] = node->val;

				node_que.push(node->left);
				node_que.push(node->right);
				depth_que.push(depth+1);
				depth_que.push(depth+1);
			}
		}

		for(int i = 1;i<=max_depth;i++) {
			vec.push_back(dep_rightval_map[i]);
		}
		return vec;
	}


};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值