美文网首页
Leetcode 513. Find Bottom Left T

Leetcode 513. Find Bottom Left T

作者: 岛上痴汉 | 来源:发表于2017-09-18 12:47 被阅读0次

原题地址:https://leetcode.com/problems/find-bottom-left-tree-value/description/

题目描述

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

即找到一棵树最底层最左边的值返回。

解题思路

一开始是误认为树除了叶子层以外都是满的,所以只想着中序遍历存到vector里最后计算出下标取出目标值,但是发现每一层不都是满的,所以想用双重循环写个深度优先遍历,外重循环每一重对应一层,内重循环对应每一层里的各个节点,然而似乎会超时。
所以我最后的做法是进行深度优先遍历,深度优先遍历函数有个参数记录当前的深度。设一个变量deepest_first,记录已经访问到的最大深度,如果深度优先遍历的当前深度大于这个最大深度,就更新最大深度的值,并取出当前节点的值。因为深度优先遍历里是先递归左子节点,再递归右子节点,所以这样执行到最后得到的就是最深处最左的节点值。

代码

/**
 * 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 first_deepest=0;
    int target = 0;
        
    void DFS(TreeNode* root,int current_level){
        if(root==NULL){
            return ;
        }
        current_level+=1;
        if(current_level>first_deepest){
            first_deepest = current_level;
            target = root->val;
        }
        DFS(root->left,current_level);
        DFS(root->right,current_level);
    }
    
    int findBottomLeftValue(TreeNode* root) {
        DFS(root,0);
        return target;
    }            
};

相关文章

网友评论

      本文标题:Leetcode 513. Find Bottom Left T

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