513 Find Bottom Left Tree Value 找树左下角的值

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

详见:https://leetcode.com/problems/find-bottom-left-tree-value/description/

C++:

方法一:

/**
 * 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;
        }
        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);
    }
};

 方法二:

/**
 * 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;
        }
        int res=root->val;
        queue<TreeNode*> que;
        que.push(root);
        while(!que.empty())
        {
            int n=que.size();
            for(int i=0;i<n;++i)
            {
                root=que.front();
                que.pop();
                if(i==0)
                {
                    res=root->val;
                }
                if(root->left)
                {
                    que.push(root->left);
                }
                if(root->right)
                {
                    que.push(root->right);
                }
            }
        }
        return res;
    }
};

 参考:http://www.cnblogs.com/grandyang/p/6405128.html

posted on 2018-04-22 15:57  lina2014  阅读(188)  评论(0编辑  收藏  举报

导航