zoukankan      html  css  js  c++  java
  • LeetCode404. 左叶子之和

    ☆方法1:递归

    方法2:BFS

    class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            /**
             * 方法1:递归
             */
            if (root == null) return 0;
            // 对当前节点进行处理
            int count = 0;
            if (root.left != null && root.left.left == null && root.left.right == null) {
                count = root.left.val;
            }
            // 当前节点 + 其左右子树的
            return count + sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);
            /**
             * 方法2:BFS
             */
            /*if (root == null) return 0;
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            int count = 0;
            while (!queue.isEmpty()) {
                int size = queue.size();
                for (int i = 0; i < size; i++) {
                    TreeNode cur = queue.poll();
    
                    if (cur.left != null) {
                        queue.offer(cur.left);
                        // 保证是叶子节点
                        if (cur.left.left == null && cur.left.right == null) {
                            count += cur.left.val;
                        }
                    }
                    if (cur.right != null) {
                        queue.offer(cur.right);
                    }
                }
            }
            return count;
            */
        }
    }
  • 相关阅读:
    springBoot 与 springMVC的区别
    spring的IOC和AOP
    实现同步的三种方法
    台阶积水问题
    requsets模块和beautifulsoup模块
    爬虫
    rabbitMQ 消息队列
    Django框架
    mysql
    jQuery
  • 原文地址:https://www.cnblogs.com/HuangYJ/p/14172052.html
Copyright © 2011-2022 走看看