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;
}