zoukankan      html  css  js  c++  java
  • 513. Find Bottom Left Tree Value

    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);
        }
    }
  • 相关阅读:
    Object类学习
    Thread.State 线程状态
    Thread.UncaughtExceptionHandler
    apply和call的区别
    如何实现border-width:0.5px;
    table固定头部,表格tbody可上下左右滑动
    canvas画布实现手写签名效果
    ES6学习笔记
    for循环中执行setTimeout问题
    javaScript函数提升及作用域
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/12230207.html
Copyright © 2011-2022 走看看