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.

    现在开始考bfs 了吗, 根据size办事,分情况了

    public int findBottomLeftValue(TreeNode root) {
            if (root == null) return -1;
            Queue<TreeNode> q = new LinkedList<>();
            q.offer(root);
            int ans = 1;
            while (!q.isEmpty()) {
                int size = q.size();
                for (int i = 0; i < size; i++) {
                    TreeNode cur = q.poll();
                        
                        if (cur.left != null) {
                            q.offer(cur.left);
                        }
                        if (cur.right != null) {
                            q.offer(cur.right);
                        }
                    if (i == 0) {
                        ans = cur.val;
                    }
                }
            }
            return ans;
        }
    

    dfs: 先序遍历  + 树的深度, 跟此题类似: 199 Binary Tree Right Side View

    public class Solution {
        int deep = 0;
        int ans = -1;
        public int findBottomLeftValue(TreeNode root) {
            if (root == null) return -1;
            //int curDeep = 0;
            dfs(root, 0);
            return ans;
        }
        private void dfs(TreeNode root, int curDeep) {
            if (root == null)  {
                return;
            }
            if (root.left ==  null && root.right == null && deep == curDeep) {
                deep++;
                ans = root.val;
                return;
            }
            if (deep == curDeep) {
                deep++;
                //curDeep++;
            }
            dfs(root.left, curDeep + 1);
            dfs(root.right, curDeep + 1);
                
        }
    }
    

      

     

  • 相关阅读:
    需求分析的方法与实践
    系统架构分析与设计方法论
    装修-3
    装修-2
    装修-1
    daikuan
    JAVA容器全面总结
    超图8C iserver启动成功,访问不了网站localhost:8090/iserver/manager,显示404
    Arcgis中给字段添加属性域
    arcgis for server搭建集群环境
  • 原文地址:https://www.cnblogs.com/apanda009/p/7295517.html
Copyright © 2011-2022 走看看