zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    LC 357. Count Numbers with Unique Digits
    LC 851. Loud and Rich
    LC 650. 2 Keys Keyboard
    LC 553. Optimal Division
    LC 672. Bulb Switcher II
    LC 413. Arithmetic Slices
    LC 648. Replace Words
    LC 959. Regions Cut By Slashes
    Spring框架学习之注解配置与AOP思想
    Spring框架学习之高级依赖关系配置(二)
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8907721.html
Copyright © 2011-2022 走看看