leetcode513 FindBottomLeftTreeValue Java
来源:互联网 发布:js获取当前日期 函数 编辑:程序博客网 时间:2024/05/22 13:29
Description
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.
解法1
递归算法 很好理解
int res = 0,h = 0;public int findBottomLeftValue(TreeNode root) { findBottomLeftValue(root, 1); return res;}public void findBottomLeftValue(TreeNode root, int depth) { if(h < depth) {res=root.val; h=depth;} if(root.left != null) findBottomLeftValue(root.left, depth+1); if(root.right !=null) findBottomLeftValue(root.right, depth+1);}
解法2
非递归 顺序遍历,用队列存储每一行的节点。循环结束,队列中的第一个即为结果。
public int findBottomLeftValue(TreeNode root) { int result = 0; Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); while(! queue.isEmpty()) { int size = queue.size(); for(int i=0; i<size; i++) { TreeNode curr = queue.poll(); if(i == 0) result = curr.val; if(curr.left != null) queue.offer(curr.left); if(curr.right != null) queue.offer(curr.right); } } return result;}
0 0
- leetcode513 FindBottomLeftTreeValue Java
- leetcode513
- leetcode513
- LeetCode513
- LeetCode513. Find Bottom Left Tree Value题解
- leetcode513. Find Bottom Left Tree Value
- Leetcode513. Find Bottom Left Tree Value
- LeetCode513. Find Bottom Left Tree Value
- 24.leetCode513:Find Bottom Left Tree Value
- python--leetcode513. Find Bottom Left Tree Value
- 【Leetcode513 Find Bottom left Tree Value】树的遍历
- java
- JAVA
- JAVA
- JAVA
- java
- Java
- Java
- Quick Sort In Haskell
- vs2013winpacp的使用
- toolbar中设置menu收起图标颜色以及popupwindow弹出位置
- 代码混淆的一些基本常识代码
- js中的变量名和函数名重名问题
- leetcode513 FindBottomLeftTreeValue Java
- linux的shell简介bash的基本功能
- 程序开发名词汇总
- 一行js代码破解百某Du云大文件下载限制
- Hadoop: File could only be replicated to 0 nodes instead of minReplication (=1). There are 1 datanod
- Android /iPhone/iPad UI之常用图标尺寸规范
- GAT-解决用车审批中,如果调度车辆是通过Excel导入的车辆,会有错误提示Bug
- s188.com 10% Cash Back Promotion on Tuesday
- Apache Thrift