[LeetCode]Find Bottom Left Tree Value 寻找二叉树最左树叶的值

声明:原题目转载自LeetCode,解答部分为原创

Problem :

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

Example 1:

Input:

    2
   / \
  1   3

Output:
1

Example 2: 

Input:

        1
       / \
      2   3
     /   / \
    4   5   6
       /
      7

Output:
7

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

Solution:

        思路:节点寻找二叉树的最底层的最左边的叶子节点的值,可以用层序遍历的方法,只需要将插入顺序由“中——左——右”改为“中——右——左”即可。

        代码如下:

#include
   
    
#include
    
     
#include
     
      
using namespace std;

//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) {
        if(!root)
        	return 0;
        
        stack
      
        record;
        queue
       
         travel; travel.push(root); while(!travel.empty()) { TreeNode* temp; temp = travel.front(); TreeNode insert(temp->val); record.push(insert); travel.pop(); if(temp->right) travel.push(temp->right); if(temp->left) travel.push(temp->left); } TreeNode leftmost = record.top(); return leftmost.val; } }; int main() { TreeNode* root_0 = new TreeNode(2); TreeNode* node_l = new TreeNode(1); TreeNode* node_r = new TreeNode(3); root_0->left = node_l; root_0->right = node_r; TreeNode* root_1 = new TreeNode(1); TreeNode* node_1 = new TreeNode(2); TreeNode* node_2 = new TreeNode(3); TreeNode* node_3 = new TreeNode(4); TreeNode* node_4 = new TreeNode(5); TreeNode* node_5 = new TreeNode(6); TreeNode* node_6 = new TreeNode(7); root_1->left = node_1; root_1->right = node_2; node_1->left = node_3; node_2->left = node_4; node_2->right = node_5; node_4->left = node_6; Solution text_0; cout << text_0.findBottomLeftValue(root_0) << endl; cout << text_0.findBottomLeftValue(root_1) << endl; return 0; }
       
      
     
    
   


版权声明:本文为xblog_原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。