LeetCode 513 Find Bottom Left Tree Value(二叉树层序遍历)

来源:互联网 发布:怎么免费做网络推广 编辑:程序博客网 时间:2024/06/11 03:34

Given a binary tree, find the leftmost value in the last row of the tree.

Example 1:

Input:    2   / \  1   3Output:1

Example 2: 

Input:        1       / \      2   3     /   / \    4   5   6       /      7Output:7

Note: You may assume the tree (i.e., the given root node) is not NULL.

题目大意:给出一棵二叉树,求这棵树最底层最左边的节点值。

解题思路:又是一道层序遍历可以做的题。用数组保存每一层的第一个元素,最后返回数组中最后一个元素即可。

代码如下:

/** * 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) {        levelOrderTraversal(root, 0, ans);        return ans.back();    }private:    queue<TreeNode*> que;    vector<int> ans;        //非递归版本    void levelOrderTraversal(TreeNode* root, vector<int>& ans) {        if(root == nullptr) return ;        TreeNode* tmp;        que.push(root);        int cur = 0;        while(cur < que.size()) {            int last = que.size();            tmp = que.front();            ans.push_back(tmp->val);            while(cur < last) {                tmp = que.front();                que.pop();                if(tmp->left) que.push(tmp->left);                if(tmp->right) que.push(tmp->right);                cur++;            }            cur = 0;        }    }        //递归版本    void levelOrderTraversal(TreeNode* root, int depth, vector<int>& ans) {        if(root == nullptr) return ;        if(depth == ans.size()) ans.push_back(root->val);        if(root->left) levelOrderTraversal(root->left, depth + 1, ans);        if(root->right) levelOrderTraversal(root->right, depth + 1, ans);    }};