https://leetcode.com/problems/find-bottom-left-tree-value/description/
Solution 1
int findBottomLeftValue(TreeNode* root) {
queue<TreeNode*> q;
q.push(root);
q.push(nullptr);
int res;
TreeNode* last = nullptr;
while(q.size()>1) {
if(last == nullptr) res = q.front()->val;
last = q.front();
q.pop();
if(last == nullptr) {
q.push(nullptr);
}
else {
if(last->left) q.push(last->left);
if(last->right) q.push(last->right);
}
}
return res;
}
Solution 2. Recursion
void findLeft(TreeNode* node, int& mx, int& maxDep, int dep) {
if(!node) return;
if(maxDep < dep) {
maxDep = dep;
mx = node->val;
}
findLeft(node->left, mx, maxDep, dep+1);
findLeft(node->right, mx, maxDep, dep+1);
}
int findBottomLeftValue(TreeNode* root) {
int mx = root->val, maxDep = 0;
findLeft(root, mx, maxDep, 0);
return mx;
}
No comments:
Post a Comment