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.
找出树左下角的值。
利用层次遍历和hashmap的key唯一性。
层次遍历二叉树,用hashmap来存储每一层的第一个节点,key为层数,value为节点值。
最后返回hashmap值为层数的那个value即可
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ static int layer = 0; class Solution { public: int findBottomLeftValue(TreeNode* root) { queue<TreeNode*> q; q.push(root); unordered_map<int, TreeNode*> m; while (!q.empty()) { int n = q.size(); layer++; for (int i = 0; i < n; i++) { TreeNode* curNode = q.front(); q.pop(); m.insert({layer, curNode}); if (curNode->left != nullptr) q.push(curNode->left); if (curNode->right != nullptr) q.push(curNode->right); } } return m[layer]->val; } }; // 13 ms