题目链接:https://leetcode.cn/problems/find-bottom-left-tree-value/
这道题也没做出来,之前的想法是递归遍历,想到把depth传递给递归函数,但是没把最深的depth和val在递归过程中保存下来,而是在递归函数里返回了val,所以就少实现了最深这个条件。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: /* void walk(TreeNode* node, int depth, int &curDep, int &curVal) { depth++; if (node->left) { walk(node->left, depth, curDep, curVal); } if (node->right) { walk(node->right, depth, curDep, curVal); } if (depth > curDep) { curDep = depth; curVal = node->val; } } int findBottomLeftValue(TreeNode* root) { int depth = 0; int curDep = 0; int curVal = root->val; walk(root, depth, curDep, curVal); return curVal; } */ int findBottomLeftValue(TreeNode* root) { int curVal = root->val; queue<TreeNode*> q; q.push(root); while (!q.empty()) { auto p = q.front(); q.pop(); curVal = p->val; if (p->right) { q.push(p->right); } if (p->left) { q.push(p->left); } } return curVal; } }; |