前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode39|找树左下角的值

LeetCode39|找树左下角的值

作者头像
码农王同学
发布2020-08-25 11:26:19
2230
发布2020-08-25 11:26:19
举报
文章被收录于专栏:后端Coder后端Coder

1,问题简述

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

2,示例

代码语言:javascript
复制
输入:

    2
   / \
  1   3

输出:
1


输入:

        1
       / \
      2   3
     /   / \
    4   5   6
       /
      7

输出:
7
注意: 您可以假设树(即给定的根节点)不为 NULL。

3,题解思路

队列的使用

4,题解程序

代码语言:javascript
复制
 
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class FindBottomLeftValueTest {
    public static void main(String[] args) {
        TreeNode t1 = new TreeNode(2);
        TreeNode t2 = new TreeNode(1);
        TreeNode t3 = new TreeNode(3);
        t1.left = t2;
        t1.right = t3;
        int bottomLeftValue = findBottomLeftValue(t1);
        System.out.println("bottomLeftValue = " + bottomLeftValue);

        int leftValue = findBottomLeftValue2(t1);
        System.out.println("leftValue = " + leftValue);
    }

    public static int findBottomLeftValue(TreeNode root) {
        if (root == null) {
            return 0;
        }
        List<List<Integer>> listList = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                list.add(node.val);
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
            listList.add(list);
        }
        return listList.get(listList.size() - 1).get(0);
    }

    public static int findBottomLeftValue2(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int result = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                result = node.val;
                if (node.right != null) {
                    queue.add(node.right);
                }
                if (node.left != null) {
                    queue.add(node.left);
                }

            }
        }
        return result;
    }
}

5,题解程序图片版

6,总结

队列的使用。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-08-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 码农王同学 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档