zoukankan      html  css  js  c++  java
  • [leetCode]404. 左叶子之和

    题目

    链接:https://leetcode-cn.com/problems/sum-of-left-leaves

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

    示例:
    
        3
       / 
      9  20
        /  
       15   7
    
    在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24
    

    递归

    判断当前节点是不是左叶子是无法判断的,必须要通过节点的父节点来判断其左孩子是不是左叶子。

    if (node->left != NULL && node->left->left == NULL && node->left->right == NULL) {
        左叶子节点处理逻辑
    }
    

    递归三步走:

    1. 确定函数返回值与函数参数
    2. 确定退出条件
    3. 确定单层逻辑
    
    class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            if (root == null) return 0;
            int leftValue = sumOfLeftLeaves(root.left);
            int rightValue = sumOfLeftLeaves(root.right);
    
            int midValue = 0;
            if (root.left != null && root.left.left == null && root.left.right == null)
                midValue = root.left.val;
            int sum = leftValue + rightValue + midValue;
            return sum;
        }
    }
    

    迭代

    使用先序或者后序遍历都可以

    class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            if (root == null) return 0;
            LinkedList<TreeNode> stack = new LinkedList<>();
            stack.push(root);
            int sum = 0;
            while (!stack.isEmpty()) {
                TreeNode node = stack.pop();
                if (node != null) {
                    stack.push(node);
                    stack.push(null);
                    if (node.right != null)
                        stack.push(node.right);
                    if (node.left != null) {
                        stack.push(node.left);
                    }
                } else {
                    TreeNode cur = stack.pop();
                    if (cur.left != null && cur.left.left == null && cur.left.right == null) {
                        sum += cur.left.val;
                    }
                }
            }
            return sum;
        }
    }
    
  • 相关阅读:
    Oracle exp/imp导出导入命令及数据库备份 (转载)
    多表初始化
    调用别的窗体
    修复k8s内存泄露问题
    如何高效的学习(转)
    Ansible11:变量详解【转】
    沟通的方式方法
    shell中的循环及条件判断
    Tomcat参数优化
    将DataReader转化为DataTables的一个简单实现
  • 原文地址:https://www.cnblogs.com/PythonFCG/p/13919688.html
Copyright © 2011-2022 走看看