513[Medium]:Find Bottom Left Tree Value

Part1:问题描述

Given a binary tree, find the leftmost value in the last row of the tree.

Example 1:

Input:

    2
   / \
  1   3

Output:
1

Example 2: 

Input:

        1
       / \
      2   3
     /   / \
    4   5   6
       /
      7

Output:
7

Note: You may assume the tree (i.e., the given root node) is not NULL.


Part2:解题思路

题目要求的问题很简单,二叉树最左边的节点的值<=>利用深搜从左到右遍历找到的深度最深的第一个元素。递归的代码很简单,但是不好理解,所以,我采用非递归开2个stack的方式解决这个问题。

由于我们想要找到的是层数最深的最左边的元素,所以我们应该从左边的分支开始遍历并记录已经访问的节点的层数depth,并通过不断的比较得到最先到达maxDepth层的那个节点,就是我们要找的最左边的节点。

由于我用的是stack,先进后出,我们想要达到先访问左边分支的目的,就要先让右边的节点进栈。

我与遇到的一个小问题:将currentDepth压栈的时候,最开始是写的currentDepth++,导致比较的时候出现问题结果不正确,后来举了一组简单的数据进行分析发现了这个问题。

Part3:代码

我只贴了leetcode上需要的那个函数

int findBottomLeftValue(TreeNode* root) {
	int maxDepth = 0;
	int leftValue = root->val;
	
	stack<TreeNode*> node;
	stack<int> depth;
	TreeNode* currentNode;
	int currentDepth = 0;
	
	node.push(root);
	depth.push(currentDepth);
	while(!node.empty()) {
		currentNode = node.top();
		currentDepth = depth.top();
		node.pop();
		depth.pop();
		if (currentNode->right) {
			node.push(currentNode->right);
			depth.push(currentDepth + 1);
		}
		if (currentNode->left) {
			node.push(currentNode->left);
			depth.push(currentDepth + 1);
		}
		if (currentDepth > maxDepth) {
			maxDepth = currentDepth;
			leftValue = currentNode->val; 
		}
	}
	return leftValue;
} 


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值