代码随想录算法训练营第十五天 | 102.二叉树的层序遍历、226.翻转二叉树、101.对称二叉树

42 阅读1分钟

102.二叉树的层序遍历

226.翻转二叉树

101.对称二叉树

102. 二叉树的层序遍历

var levelOrder = function(root) {
    if(!root)   return [];

    const res = [];
    const q = [];
    q.push(root);
    let len = q.length;

    while (len > 0) {
        const level = [];
        while (len--) {
            const node = q.shift();
            level.push(node.val);
            if (node.left)  q.push(node.left);
            if (node.right) q.push(node.right);
        }
        len = q.length;
        res.push(level);
    }

    return res;
};

226. 翻转二叉树

  • 思路:翻转 = 重新整理一遍二叉树的节点顺序 => 适合迭代法 => 左右中 => 统一迭代法(用空节点标记中间节点)
var invertTree = function(root) {
    if (!root)  return root;

    const stk = [];
    let node = root;
    stk.push(node);

    while (node || stk.length > 0) {
        node = stk.pop();
        if (node) {
            stk.push(node);
            stk.push(null);
            if (node.right) stk.push(node.right);
            if (node.left) stk.push(node.left);
        } else {
            const currNode = stk.pop();
            const tmpR = currNode.right;
            currNode.right = currNode.left;
            currNode.left = tmpR;
        }
    }

    return root;
};

101. 对称二叉树

  • 感想:总想不到这不是节点的比较,自己写会用一个根节点的左右子树比两层,导致总有遗漏case。实际上应该用两棵子树来比,即直接用根节点比。
var isSymmetric = function(root) {
    const isSubSym = (leftR, rightR) => {
        if (!leftR && !rightR)  return true;
        if (!leftR && rightR)  return false;
        if (leftR && !rightR)   return false;
        if (leftR.val !== rightR.val)   return false;

        const resO = isSubSym(leftR.left, rightR.right);
        const resI = isSubSym(leftR.right, rightR.left);
        return resO && resI;
    }

    if (!root)  return true;
    return isSubSym(root.left, root.right);
};