LeetCode513

来源:互联网 发布:怎么淘宝放单子 编辑:程序博客网 时间:2024/05/22 15:55

EX. 513

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

Example1:

Input:    2   / \  1   3Output:1

Example2:

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

Solution:

只需在每一次DFS时,先访问左边,且只在深度大于当前长度时,才更新res的值,并更新当前长度

/** * 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) {        int bottomLeft = 0;        int height = 0;        dfs(root, 1, height, bottomLeft);        return bottomLeft;    }private:    void dfs(TreeNode* node, int depth, int& height, int& res) {        if (!node) {            return;        }        if (depth > height) {            res = node->val;            height = depth;        }        dfs(node->left, depth + 1, height, res);        dfs(node->right, depth + 1, height, res);    }};