zoukankan      html  css  js  c++  java
  • 二叉树的左叶子之和

    Leetcode题目描述

    计算给定二叉树的所有左叶子之和。

    示例:

        3
       / 
      9  20
        /  
       15   7
    

    在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24

    广度优先解答

    • 依次遍历 判断是否是左节点并且是否为叶子节点.如果是加入计算.否则跳过

    广度优先解答demo

    class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            if (root == null ) return 0;
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            int sum = 0;
    
            queue.offer(root);
            while(!queue.isEmpty()){
                TreeNode first = queue.poll();
                if(first.left != null){
                    queue.offer(first.left);
                    TreeNode tmp = first.left;
                    if(tmp.left == null && tmp.right == null){
                        sum = sum + tmp.val;
                    }
                }
                if(first.right != null){
                    queue.offer(first.right);
                }
            }
            return sum;
        }
    }
    

    总结

    • 少用广度优先,就是采用对队列的方式,不知道如何判断队列是否为空,判断队列是否为空的重要方式是!queue.isEmpty用来判断队列是否为空
  • 相关阅读:
    POJ测试数据合集
    POJ1724ROADS
    关闭进程的数据库
    config上传设置
    tfs 撤销挂起的更改
    cn_visual_studio_team_foundation_server_2010_x86_x64_dvd_531909
    js 中文转义
    文件下载乱码
    杀死数据库进程
    Python基础综合练习
  • 原文地址:https://www.cnblogs.com/Di-iD/p/13784914.html
Copyright © 2011-2022 走看看