LeetCode刷题记录(JavaScript)——二叉树

目录

104. 二叉树的最大深度(easy)——03/22

617. 合并二叉树(easy) ——04/10

100. 相同的树(easy) —— 04/10

110. 平衡二叉树(easy) ——04/10

637. 二叉树的层平均值(easy)——04/17

226. 翻转二叉树(easy)——04/17

235. 二叉搜索树的最近公共祖先(easy)——04/17

111. 二叉树的最小深度(easy) ——04/17


104. 二叉树的最大深度(easy)——03/22

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7]

    3
   / \
  9  20
    /  \
   15   7

返回它的最大深度 3 。

 

递归
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var maxDepth = function(root) {
    if (root ==null) return 0 ;
    let left = maxDepth(root.left);
    let right = maxDepth(root.right);
    return Math.max(left,right)+1;
};

617. 合并二叉树(easy) ——04/10

给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。

你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值,否则不为 NULL 的节点将直接作为新二叉树的节点。

示例 1:

输入: 
    Tree 1                     Tree 2                  
          1                         2                             
         / \                       / \                            
        3   2                     1   3                        
       /                           \   \                      
      5                             4   7                  
输出: 
合并后的树:
         3
        / \
       4   5
      / \   \ 
     5   4   7
注意: 合并必须从两个树的根节点开始。

解题思路:

 1.从根节点开始,递归,前序遍历思想, 将t2合并到t1上面: 

如果t1为空,则取t2,如果t2为空,取t1,如果都不空,那么计算新值,并且对它们的左孩子,右孩子进行合并,返回

2.非递归: 实际上是广度优先(层序遍历),如果t1,t2有一个是null,就直接返回非空,如果都不空,那么就进入队列循环

循环中:取出节点,计算合并值,赋给t1,判断 两个left,如果都非空,那么进入队列,再判断 两个right,如果都非空,那么也进入队列。否则谁不为空,就赋给t1。直到队列空了

最后返回t1即可


/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} t1
 * @param {TreeNode} t2
 * @return {TreeNode}
 */

1.递归
var mergeTrees = function(t1, t2) {
    if (t1 == null){
        return t2;
    }
    else if (t2 == null){
        return t1;
    } else {
        t1.val  = t1.val + t2.val;
        t1.left  = mergeTrees(t1.left,t2.left);
        t1.right = mergeTrees(t1.right,t2.right);
        return t1;
    }
};


2.非递归
var mergeTrees = function(t1, t2) {
    if (t1 == null || t2 == null){
        return t1 ? t1 :t2;
    } 
    let queue = [];
    queue.push([t1,t2]);
    while(queue.length > 0) {
        let [p,q] = queue.shift(); 
        p.val += q.val;

        if (p.left == null || q.left == null){
            p.left = p.left ? p.left : q.left;
        }else {
            queue.push([p.left,q.left]);
        }
        
        if (p.right == null || q.right == null){
            p.right = p.right ? p.right : q.right;
        }else {
            queue.push([p.right,q.right]);
        }
    }
    return t1;
};

100. 相同的树(easy) —— 04/10

给定两个二叉树,编写一个函数来检验它们是否相同。

如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。

示例 1:

输入:       1         1
          / \       / \
         2   3     2   3

        [1,2,3],   [1,2,3]

输出: true

示例 2:

输入:      1          1
          /           \
         2             2

        [1,2],     [1,null,2]

输出: false

解题思路:

 递归:

p,q都是null ——> true

p,q 一个是null,一个不是 ——> false

p,q 值不相等 ——> false

p,q 值相等 ——> 判断left 和 right;  取 并 

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {boolean}
 */

var isSameTree = function(p, q) {
    if (p == null && q == null){
        return true;
    }else if (p == null || q == null){
        return false;
    }else if (p.val != q.val){
        return false; 
    }

    return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
};

110. 平衡二叉树(easy) ——04/10

给定一个二叉树,判断它是否是高度平衡的二叉树。

本题中,一棵高度平衡二叉树定义为:

一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。

示例 1:

给定二叉树 [3,9,20,null,null,15,7]

    3
   / \
  9  20
    /  \
   15   7
返回 true 。

解题思路: 

-1时代表失败,直接返回

否则递归查询,递归出口是root == null ,返回高度0

递归查询左右子树高度,如果高度差绝对值<2,那么该节点是平衡的,它的高度等于左右高度的max+1,否则不平衡,直接-1

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 */
var isBalanced = function(root) {
    return checkBalanced(root) != -1;
};

var checkBalanced = function(root){
    if (root == null) return 0;
    let left = checkBalanced(root.left);
    if (left == -1) return -1;
    let right = checkBalanced(root.right);
    if (right == -1) return -1;
    return Math.abs(left - right) < 2 ? Math.max(left,right)+1 : -1;
};

637. 二叉树的层平均值(easy)——04/17

给定一个非空二叉树, 返回一个由每层节点平均值组成的数组.

示例 1:

输入:
    3
   / \
  9  20
    /  \
   15   7
输出: [3, 14.5, 11]
解释:
第0层的平均值是 3,  第1层是 14.5, 第2层是 11. 因此返回 [3, 14.5, 11].
注意:

节点值的范围在32位有符号整数范围内。

解题思路:

广度优先遍历,类似于层次遍历,用queue来存储每层的节点,但是为了计算每层节点数量,借助临时队列temp来存储下一层的节点,这样方便计算本层数量,及本层sum值,在计算完成后再把temp赋值给queue。

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var averageOfLevels = function(root) {
    let result = [],queue = [];
    if (!root) return result;
    queue.push(root);
    while(queue.length>0){
        let count = 0, sum = 0, temp=[];
        while(queue.length>0){
            let node = queue.shift();
            count ++;
            sum += node.val;
            if (node.left) temp.push(node.left);
            if (node.right) temp.push(node.right);
        }
        queue = temp;
        result.push(sum/count);
    }
    return result;
};

226. 翻转二叉树(easy)——04/17

翻转一棵二叉树。

示例:

输入:

     4
   /   \
  2     7
 / \   / \
1   3 6   9
输出:

     4
   /   \
  7     2
 / \     / \
9   6 3   1

解题思路:

递归,后序,先处理左孩子,右孩子,最后把左右孩子调换。

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {TreeNode}
 */
var invertTree = function(root) {
    if (!root) return root;
    root.left = invertTree(root.left);
    root.right = invertTree(root.right);
    let temp = root.left;
    root.left = root.right;
    root.right = temp;
    return root;
};

235. 二叉搜索树的最近公共祖先(easy)——04/17

给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。

百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”

例如,给定如下二叉搜索树:  root = [6,2,8,0,4,7,9,null,null,3,5]

 

示例 1:

输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
输出: 6 
解释: 节点 2 和节点 8 的最近公共祖先是 6。
示例 2:

输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
输出: 2
解释: 节点 2 和节点 4 的最近公共祖先是 2, 因为根据定义最近公共祖先节点可以为节点本身。

解题思路:

二叉搜索树特性:左子树的值都比根的值小,右子树的值都比根的值大。

所以根据这个特性,得出方法:从根开始遍历,如果p和q都在左子树上,那么把左孩子当根再进行遍历,如果p和q都在右子树上,那么把右孩子当根进行遍历,如果p和q不在同一侧,那么这个节点就是他们的最近的公共祖先。

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {TreeNode}
 */
var lowestCommonAncestor = function(root, p, q) {
    
        let  parentVal = root.val, pVal =p.val, qVal = q.val;
        if ( pVal > parentVal && qVal > parentVal) {
            return lowestCommonAncestor(root.right, p, q);
        } else if (pVal < parentVal && qVal < parentVal) {
            return lowestCommonAncestor(root.left, p, q);
        } else {
            return root;
        }
};

111. 二叉树的最小深度(easy) ——04/17

给定一个二叉树,找出其最小深度。

最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

说明: 叶子节点是指没有子节点的节点。

示例:

给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
返回它的最小深度  2.

解题思路:

递归出口:

1.root == null,是叶子节点,0

2.root左右孩子都是null,那么它的深度是1。

3.要注意的是当有一个孩子为空,另一个孩子不空,那么它的深度要取不空孩子的深度+1;

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var minDepth = function(root) {
    if (!root) return 0;
    if (!root.left && !root.right ) return 1;
    if (!root.left || !root.right) return Math.max(minDepth(root.left),minDepth(root.right))+1;
    return Math.min(minDepth(root.left),minDepth(root.right))+1;
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值