找出该二叉树的最底层最左边节点的值。
需要理解最底层最左边的意思。实际上就是根据深度获得最底层节点,深度变大就更新result,然后遍历的时候按中左右,先遍历左子树,这样一来result存的就会是最底层最左边的那个元素。
class Solution {
public:
int result=0;
int max_depth=-1;
int findBottomLeftValue(TreeNode* root) {
traverse(root,0);
return result;
}
void traverse(TreeNode* root,int depth){
if(root==nullptr) return;
if(!root->left&&!root->right&&depth>max_depth){
max_depth=depth;
result=root->val;
}
traverse(root->left,depth+1);
traverse(root->right,depth+1);
}
};