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