首页 > 其他 > 详细

[LeetCode] Find Bottom Left Tree Value 寻找最左下树结点的值

时间:2017-02-16 14:05:23      阅读:324      评论:0      收藏:0      [点我收藏+]

 

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.

 

这道题让我们求二叉树的最左下树结点的值,也就是最后一行左数第一个值,那么我首先想的是用先序遍历来做,我们维护一个最大深度和该深度的结点值,由于先序遍历遍历的顺序是左-根-右,所以每一行最左边的结点肯定最先遍历到,那么由于是新一行,那么当前深度肯定比之前的最大深度大,所以我们可以更新最大深度为当前深度,结点值res为当前结点值,这样在遍历到该行其他结点时就不会更新结果res了,参见代码如下:

 

解法一:

class Solution {
public:
    int findLeftMostNode(TreeNode* root) {
        if (!root) return 0;
        int max_depth = 1, res = root->val;
        helper(root, 1, max_depth, res);
        return res;
    }
    void helper(TreeNode* node, int depth, int& max_depth, int& res) {
        if (!node) return;
        if (depth > max_depth) {
            max_depth = depth;
            res = node->val;
        }
        helper(node->left, depth + 1, max_depth, res);
        helper(node->right, depth + 1, max_depth, res);
    }
};

 

其实这道题用层序遍历更直接一些,因为层序遍历时遍历完当前行所有结点之后才去下一行,那么我们再遍历每行第一个结点时更新结果res即可,根本不用维护最大深度了,参见代码如下:

 

解法二:

class Solution {
public:
    int findBottomLeftValue(TreeNode* root) {
        if (!root) return 0;
        int res = 0;
        queue<TreeNode*> q;
        q.push(root);
        while (!q.empty()) {
            int n = q.size();
            for (int i = 0; i < n; ++i) {
                TreeNode *t = q.front(); q.pop();
                if (i == 0) res = t->val;
                if (t->left) q.push(t->left);
                if (t->right) q.push(t->right);
            }
        }
        return res;
    }
};

 

参考资料:

 

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Find Bottom Left Tree Value 寻找最左下树结点的值

原文:http://www.cnblogs.com/grandyang/p/6405128.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!