LeetCode刷题 Day17

71 阅读2分钟

LeetCode刷题 Day17

110. Balanced Binary Tree

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as:

a binary tree in which the left and right subtrees of every node differ in height by no more than 1.

 

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: true

Example 2:

Input: root = [1,2,2,3,3,null,null,4,4]
Output: false

Example 3:

Input: root = []
Output: true

思路:

  • 这道题和算最大高度的题是一样的,只是在后序遍历的过程中加一个判断逻辑, abs(left - right) > 1

代码:

var isBalanced = function(root) {
    let isBalancedTree = true;
    
    var helper = function(root) {
        if (!root) return 0;
    
        let leftHeight = helper(root.left);
        let rightHeight = helper(root.right);

        if (Math.abs(leftHeight - rightHeight) > 1) isBalancedTree = false;

        return 1 + Math.max(leftHeight, rightHeight);
    }
    
    helper(root);
    return isBalancedTree;
};

时间复杂度: O(n),空间复杂度: O(n) 这个空间复杂度是最差情况


257. Binary Tree Paths

Given the root of a binary tree, return all root-to-leaf paths in any order.

leaf is a node with no children.

 

Example 1:

Input: root = [1,2,3,null,5]
Output: ["1->2->5","1->3"]

Example 2:

Input: root = [1]
Output: ["1"]

思路:

  • 这是一个典型的回溯法, 有一点需要注意, 如果是使用数组作为path。那么在后序遍历的阶段需要做path.pop()。因为数组是引用类型,做了地址拷贝。 而如果使用了string作为path,那么不需要任何的后序操作,因为string是原始类型,只是内容拷贝,在返回上一层后就没有之前的信息保存下来了。

代码:

var binaryTreePaths = function(root) {
    let res = [];
    
    var helper = function(root, path, test) {
        if (!root) return;
        
        if(!root.left && !root.right) {
            path += root.val;
            res.push(path);
            return;
        }
        
        path += root.val + '->';
        if (root.left) {
            helper(root.left, path, test);
        }
        
        if (root.right) {
            helper(root.right, path);
        }
        
    }
    
    helper(root, '');
    return res;
};

时间复杂度: O(N) 空间复杂度: O(N)


404. Sum of Left Leaves

Given the root of a binary tree, return the sum of all left leaves.

leaf is a node with no children. A left leaf is a leaf that is the left child of another node.

  Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: 24
Explanation: There are two left leaves in the binary tree, with values 9 and 15 respectively.

Example 2:

Input: root = [1]
Output: 0

思路:

  • 在递归过程存储父节点,这样可以比较容易获得 parent.left === root的信息。
  • 判断 parent && parent.left === root && !root.left && !root.right

代码:

var sumOfLeftLeaves = function(root) {
    let sum = 0;
    
    var helper = function(root, parent) {
        if (!root) return;
        
        helper(root.left, root);
        helper(root.right, root);
        
        if (parent && parent.left === root && !root.left && !root.right) {
            sum += root.val;
        }
    }
    
    helper(root, null);
    return sum;
};

时间复杂度: O(N) 空间消耗比较大,因为存储了父节点。可以参考其他方法将空间消耗降为O(N)leetcode.com/problems/su…