[路飞]算法:树的子结构

132 阅读2分钟

剑指 Offer 26. 树的子结构

正题

输入两棵二叉树A和B,判断B是不是A的子结构。(约定空树不是任意一个树的子结构)

B是A的子结构, 即 A中有出现和B相同的结构和节点值。

例如:
给定的树 A:

     3
    / \
   4   5
  / \
 1   2

给定的树 B:

   4 
  / \
 1

返回 true,因为 B 与 A 的一个子树拥有相同的结构和节点值。

示例 1:

输入: A = [1,2,3], B = [3,1]
输出: false

示例 2:

输入: A = [3,4,5,1,2], B = [4,1]
输出: true

解析:

判断是否为子树结构从根本和最直观的判断方式就是:

(划重点!!)在遍历A的同时,B使用同样的遍历方法,他们是否会在某一节点重合重合,直至B遍历结束

拿实例2作为参考,我们利用动画来解释一下。

1.gif

开始写代码

  1. 根据题干 (约定空树不是任意一个树的子结构),最先撸一行
if (B === null) {
    return false
}
  1. 通过栈的方式遍历A树
const stack = [A]
while(stack.length) {
    const nodeA = stack.pop()
    nodeA.right && stack.push(nodeA.right)
    nodeA.left && stack.push(nodeA.left)
}

nodeA 即为遍历过程中经过的每一个节点。不太了解二叉树的遍历可以参考之前的文章:二叉树的前序遍历

  1. 写一个方法递归判断当前节点是否与B构成父子树
var isSameTree = function (subA, B) {
    if (B === null) {
        return true // B遍历完了都没有 return false 的话,那么在这里可以 return true
    } else if (subA === null && B !== null) {
        return false // A已经没了,但是B还有,说明B不会是A的子树, return false
    }
    if (subA.val !== B.val) {
        return false // 当前节点不相等 return false
    }
    return isSameTree(subA.left, B.left) && isSameTree(subA.right, B.right) // 递归比较
}
  1. 在遍历A的过程中调用判断父子树的方法
while(stack.length) {
    const nodeA = stack.pop()
    nodeA.right && stack.push(nodeA.right)
    nodeA.left && stack.push(nodeA.left)
    if (isSameTree(nodeA, B)) {
        return true
    }
}

完整代码

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

var isSameTree = function (subA, B) {
    if (B === null) {
        return true // B遍历完了都没有 return false 的话,那么在这里可以 return true
    } else if (subA === null && B !== null) {
        return false // A已经没了,但是B还有,说明B不会是A的子树, return false
    }
    if (subA.val !== B.val) {
        return false // 当前节点不相等 return false
    }
    return isSameTree(subA.left, B.left) && isSameTree(subA.right, B.right) // 递归比较
}

var isSubStructure = function(A, B) {
    if (B === null) {
        return false
    }
    const stack = [A]
    while(stack.length) {
        const nodeA = stack.pop()
        nodeA.right && stack.push(nodeA.right)
        nodeA.left && stack.push(nodeA.left)
        if (isSameTree(nodeA, B)) {
            return true
        }
    }
    return false
};

image.png

了解二叉树的遍历,比较,理解递归在二叉树中的运用是解决这题的关键,如果都很熟练,那么又有何难呢。