513. Find Bottom Left Tree Value
来源:互联网 发布:985软件工程硕士工资 编辑:程序博客网 时间:2024/06/08 16:59
1.题目
Given a binary tree, find the leftmost value in the last row of the tree.
Example 1:
Input:
2
/ \
1 3
Output:
1
Example 2:
Input:
1 / \ 2 3 / / \4 5 6 / 7
Output:
7
Note: You may assume the tree (i.e., the given root node) is not NULL.
2.分析
这是一道树形结构的题目,寻找左子树做后一层最左边的位置,很明显的采用递归的方法。
3.解题
我的解法
class Solution {public int findBottomLeftValue(TreeNode root) { // 这道题假设树非空 int result = 0; // 最终的返回值 int depth = findDepth(root); if(depth==1){ return root.val; } if(root==null){ return 0; } int left = findDepth(root.left); int right = findDepth(root.right); if(left>=right){ result = findBottomLeftValue(root.left); // 递归左子树 }else{ result = findBottomLeftValue(root.right); // 递归右子树 } return result;}// 查找树的层数public int findDepth(TreeNode node){ if(node==null){ return 0; } if(node!=null&&node.left==null&&node.right==null){ return 1; } return Math.max(1+findDepth(node.left),1+findDepth(node.right));}}
4.总结
看了一下其他人的解法其实也是大同小异,就是递归调用中,因为寻找的是最后一层最左边的树节点,所以首先会判断,树的深度,然后比较去递归左子树或右子树,寻找它的最左数值,即为最后的结果。
阅读全文
0 0
- LeetCode 513. Find Bottom Left Tree Value
- [leetcode]513. Find Bottom Left Tree Value
- 513. Find Bottom Left Tree Value
- 513. Find Bottom Left Tree Value
- [leetcode] 513. Find Bottom Left Tree Value
- 513. Find Bottom Left Tree Value
- 513. Find Bottom Left Tree Value
- 513. Find Bottom Left Tree Value
- 【LeetCode】513. Find Bottom Left Tree Value
- 513. Find Bottom Left Tree Value
- Leetcode 513. Find Bottom Left Tree Value
- LeetCode 513. Find Bottom Left Tree Value
- [DFS]513. Find Bottom Left Tree Value
- LeetCode 513. Find Bottom Left Tree Value
- 513. Find Bottom Left Tree Value
- 【leetcode】 513. Find Bottom Left Tree Value
- 513. Find Bottom Left Tree Value | LeetCode
- 513. Find Bottom Left Tree Value
- MongoDB索引探究
- 【机器学习入门】Andrew NG《Machine Learning》课程笔记之四:分类、逻辑回归和过拟合
- 线程安全
- 概率统计——基础运算法则
- msyql 全量备份脚本
- 513. Find Bottom Left Tree Value
- Dubbo架构设计详解
- Storm通过rJava调用R脚本的环境配置
- JS中 try...catch...finally (转)
- UVA
- WebService
- sed在行首或者行尾添加内容
- 提高VS2010/VS2012编译速度
- C++中二维数组的初始化