刷題-力扣-513. 找樹左下角的值
阿新 • • 發佈:2021-08-16
513. 找樹左下角的值
題目連結
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/find-bottom-left-tree-value
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
題目描述
給定一個二叉樹的 根節點 root,請找出該二叉樹的最底層最左邊節點的值。
假設二叉樹中至少有一個節點。
示例 1:
輸入: root = [2,1,3]
輸出: 1
示例 2:
輸入: [1,2,3,4,null,5,6,null,null,7]
輸出: 7
提示:
- 二叉樹的節點個數的範圍是 [1,104]
- -231<= Node.val <= 231- 1
題目分析
- 根據題目描述獲取樹最底層最左邊的節點
- 廣度優先搜尋遍歷,當遍歷到最後一層時,第一個節點即為所求
程式碼
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int findBottomLeftValue(TreeNode* root) { TreeNode* node = root; queue<TreeNode*> nodeList; nodeList.emplace(root); while (!nodeList.empty()) { int nodeListLen = nodeList.size(); node = nodeList.front(); for (int i = 0; i < nodeListLen; ++i) { if (nodeList.front()->left) nodeList.emplace(nodeList.front()->left); if (nodeList.front()->right) nodeList.emplace(nodeList.front()->right); nodeList.pop(); } } return node->val; } };