【LeetCode】Find Bottom Left Tree Value 解题报告

来源:互联网 发布:牛股选股公式源码 编辑:程序博客网 时间:2024/06/05 04:19

【LeetCode】Find Bottom Left Tree Value 解题报告

标签(空格分隔): LeetCode


题目地址:https://leetcode.com/problems/find-bottom-left-tree-value/#/description

题目描述:

Given a binary tree, find the leftmost value in the last row of the tree.

Example:

Input:    2   / \  1   3Output:1Input:        1       / \      2   3     /   / \    4   5   6       /      7Output:7

Note: You may assume the tree (i.e., the given root node) is not NULL.

Ways

这就是所谓的BFS算法。广度优先搜索,但是搜索的顺序是有要求的,因为题目要最底层的叶子节点的最左边的叶子,那么进入队列的顺序就是先右节点再左节点,这样能把每层的节点都能从右到左过一遍,那么用一个int保存最后的节点值就可以了。

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int findBottomLeftValue(TreeNode root) {        int ans = 0;        Queue<TreeNode> tree = new LinkedList<TreeNode>();        tree.offer(root);        while(!tree.isEmpty()){            TreeNode temp = tree.poll();            if(temp.right != null){                tree.offer(temp.right);            }            if(temp.left != null){                tree.offer(temp.left);            }            ans = temp.val;        }        return ans;    }}

Date

2017 年 4 月 13 日

0 0
原创粉丝点击