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.
- class Solution {
- public int findBottomLeftValue(TreeNode root) {
- List<List<Integer>> help = levelOrder(root);
- return help.get(help.size() - 1).get(0);
- }
- public List<List<Integer>> levelOrder(TreeNode root) {
- List<List<Integer>> res = new ArrayList<>();
- Helper(0, root, res);
- return res;
- }
- public void Helper(int height, TreeNode p, List<List<Integer>> res){
- if(p == null) return;
- if(height == res.size()){
- res.add(new ArrayList());
- }
- res.get(height).add(p.val);
- Helper(height + 1, p.left, res);
- Helper(height + 1, p.right, res);
- }
- }
首先是我们的老朋友 level order
- public class Solution {
- int ans=0, h=0;
- public int findBottomLeftValue(TreeNode root) {
- findBottomLeftValue(root, 1);
- return ans;
- }
- public void findBottomLeftValue(TreeNode root, int depth) {
- if (h<depth) {ans=root.val;h=depth;}
- if (root.left!=null) findBottomLeftValue(root.left, depth+1);
- if (root.right!=null) findBottomLeftValue(root.right, depth+1);
- }
- }
来源: http://www.bubuko.com/infodetail-3392940.html