513. 找树左下角的值
解题思路
参照代码随想录
这题用层次遍历最好理解,递归用到回溯不太好理解
```cpp [] /**层次遍历 * 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) { if(root == nullptr) return 0; queue<TreeNode*> que; que.push(root); int res; while(!que.empty()){ int size = que.size(); for(int i = 0; i<size; i++){ TreeNode* node = que.front(); que.pop(); if(i == 0) res = node->val; if(node->left) que.push(node->left); if(node->right) que.push(node->right); } } return res; } }; ``` ```cpp [] /**递归 * 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 maxLen = INT_MIN; // 存放深度最大的左边 int maxLeftValue; // 存放左边最大深度的值 void traverse(TreeNode *node, int leftLen){ if(node->left == nullptr && node->right == nullptr){ if(leftLen > maxLen){ maxLen = leftLen; //更新 maxLeftValue = node->val; //更新 } return; } if(node->left){ leftLen++; traverse(node->left, leftLen); leftLen--; } if(node->right){ leftLen++; traverse(node->right, leftLen); leftLen--; } } int findBottomLeftValue(TreeNode* root) { if(root == nullptr) return 0; traverse(root, 0); return maxLeftValue; } }; ```