美文网首页
[树层遍历]LeetCode513. Find Bottom L

[树层遍历]LeetCode513. Find Bottom L

作者: wshxj123 | 来源:发表于2017-06-28 13:49 被阅读11次

求树最后一层最左的结点,采用queue层遍历,但是是从右往左,保证最后一个即所求

/**
 * 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) {
        queue<TreeNode*> q;
        TreeNode* now = root;
        q.push(now);
        while(!q.empty()) {
            now = q.front();
            q.pop();
            if(now->right != NULL)
                q.push(now->right);
            if(now->left != NULL)
                q.push(now->left);
        }
        return now->val;
    }
};

相关文章

网友评论

      本文标题:[树层遍历]LeetCode513. Find Bottom L

      本文链接:https://www.haomeiwen.com/subject/axjucxtx.html