Given a binary tree, find the leftmost value in the last row of the tree.node
Example 1:
Input:c++
2 / \ 1 3
Output:
1
Example 2:
Input:code
1 / \ 2 3 / / \ 4 5 6 / 7
Output:
7
Note: You may assume the tree (i.e., the given root node) is not NULL.队列
先求出树的高度,而后层次遍历,遍历到最后一层,输出最左边的节点(也就是最后一层第一个节点,由于层次遍历采用从左到右的方式)。it
/** * 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: int findBottomLeftValue(TreeNode* root) { int height = calcTreeHeight(root); int count = 1; queue<TreeNode*> childs, new_childs; childs.push(root); while (1) { while(!childs.empty()) { TreeNode* tmp = childs.front(); if (count == height) return tmp->val; childs.pop(); if (tmp->left != NULL) new_childs.push(tmp->left); if (tmp->right != NULL) new_childs.push(tmp->right); } count++; childs = new_childs; clear(new_childs); } } // 清空队列的方法 void clear( std::queue<TreeNode*> &q ) { std::queue<TreeNode*> empty; std::swap(q, empty ); } int calcTreeHeight(TreeNode* root) { if (root == NULL) return 0; int left = calcTreeHeight(root->left); int right = calcTreeHeight(root->right); return max(left, right) + 1; } };
直接层次遍历也能够,最后一层遍历结束后,直接输出最后一层的第一个节点便可。io
/** * 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: int findBottomLeftValue(TreeNode* root) { queue<TreeNode*> childs, new_childs; childs.push(root); while (1) { int flag = 1; TreeNode* first; while(!childs.empty()) { TreeNode* tmp = childs.front(); if (flag) { first = tmp; flag = 0; } childs.pop(); if (tmp->left != NULL) new_childs.push(tmp->left); if (tmp->right != NULL) new_childs.push(tmp->right); } if (new_childs.empty()) { return first->val; } childs = new_childs; clear(new_childs); } } void clear( std::queue<TreeNode*> &q ) { std::queue<TreeNode*> empty; std::swap( q, empty ); } };