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

  • 相关阅读:
    linux Mysql 安装
    百度地图的一些操作
    Angularjs Table
    liunx安装mongodb
    ARP协议
    Python获取IP的方式与意义
    selenium 的使用--持续更
    使用pyquery
    beautiful soup的用法
    内置函数
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8907721.html
Copyright © 2011-2022 走看看