[Sequence binary tree traversal] leetcode513: bottom left of the tree to find the value (medium)

topic:

513. find the value of the lower left corner of the tree

answer:

  • Using a sequence of binary tree traversal to find the value of the last layer of the leftmost node of attention into a queue way from right to left, thus ensuring that the last node is the last layer of the p leftmost.

code show as below:

class Solution {
public:
    //层序遍历:从右至左,这样最后一个节点的值就是最左下角的值
    int findBottomLeftValue(TreeNode* root) {
        if(!root)return -1;
        queue<TreeNode*> q;
        q.push(root);
        TreeNode* p=nullptr;
        while(!q.empty()){
            p=q.front();q.pop();
            if(p->right)q.push(p->right);
            if(p->left)q.push(p->left);
        }
        //p为最后一层最左边的节点
        return p->val;
    }
};
Published 484 original articles · won praise 149 · views 110 000 +

Guess you like

Origin blog.csdn.net/qq_43152052/article/details/103917413