【leetcode刷题笔记】513.找树左下角的值

题目

给定一个二叉树,在树的最后一行找到最左边的值。

示例 1:

输入:
2
/ \
1 3

输出:
1

示例 2:

输入:

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

输出:
7

解法一:广度优先遍历(bfs)

bfs很简单暴力,没啥好说的,同一层次结点从左往右或者从右往左依次遍历,因为这里要求最左的值,从右往左遍历一下

/**
 * 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*>tree;
        tree.push(root);
        TreeNode*node;
        while(!tree.empty())
        {
            node = tree.front();
            tree.pop();
            if(node->right)   //先放右结点
                tree.push(node->right);
            if(node->left)
                tree.push(node->left);
        }
        return node->val; 
    }
};

解法二:深度优先遍历(dfs)

dfs的关键就是不断的往下一层传,我让根节点为第1层

/**
 * 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 maxdepth = 0;
    int value = 0;
    void dfs(TreeNode* root, int depth)
    {
        if(root == NULL)
            return;
        if(depth > maxdepth)
        {
            maxdepth = depth;
            value = root->val;
        }
        if(root->left)     //因为要得到最左下角的值所以先传左结点值
            dfs(root->left,depth+1);
        if(root->right)
            dfs(root->right,depth+1);
    }
    
    int findBottomLeftValue(TreeNode*root) 
    {
       dfs(root,1);    
        return value;
        
    }
};

你可能感兴趣的:(leetcode刷题笔记)