Given a binary tree, find the leftmost value in the last row of the tree.
Example 1:
Input: 2 / \ 1 3Output:1
Example 2:
Input: 1 / \ 2 3 / / \ 4 5 6 / 7Output: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) { queueq; q.push(root); unordered_map 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
Using dfs to solve this problem.
/** * 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 val = 0; int depth = 1; int height = 0; dfs(root, depth, height, val); return val; } void dfs(TreeNode* node, int depth, int& height, int& val) { if (node == nullptr) return; if (depth > height) { val = node->val; height = depth; } dfs(node->left, depth + 1, height, val); dfs(node->right, depth + 1, height, val); }};// 13 ms