226.翻转二叉树
function invertTree(root: TreeNode | null): TreeNode | null {
function traverse(root: TreeNode){
if(!root) return;
[root.right, root.left] = [root.left, root.right];
root.left && traverse(root.left)
root.right && traverse(root.right)
}
traverse(root)
return root;
};
101. 对称二叉树 (需要回看)
递归法:
function isSymmetric(root: TreeNode | null): boolean {
if(!root) return true;
function traverse(leftNode: TreeNode | null, rightNode: TreeNode | null){
if(!leftNode && !rightNode) return true;
if(!leftNode || !rightNode) return false;
if(leftNode.val !== rightNode.val) return false;
let isSym1 = traverse(leftNode.left, rightNode.right);
let isSym2 = traverse(leftNode.right, rightNode.left);
return isSym1 && isSym2;
}
return traverse(root.left, root.right);
};
迭代法:
function isSymmetric(root: TreeNode | null): boolean {
let helperQueue: (TreeNode | null)[] = [];
let tempNode1: TreeNode | null,
tempNode2: TreeNode | null;
if (root !== null) {
helperQueue.push(root.left);
helperQueue.push(root.right);
}
while (helperQueue.length > 0) {
tempNode1 = helperQueue.shift()!;
tempNode2 = helperQueue.shift()!;
if (tempNode1 === null && tempNode2 === null) continue;
if (tempNode1 === null || tempNode2 === null) return false;
if (tempNode1.val !== tempNode2.val) return false;
helperQueue.push(tempNode1.left);
helperQueue.push(tempNode2.right);
helperQueue.push(tempNode1.right);
helperQueue.push(tempNode2.left);
}
return true;
}
104.二叉树的最大深度
function maxDepth(root: TreeNode | null): number {
let maxDepth = 0;
function traverse(root: TreeNode, level: number) {
if (!root) return;
if (level > maxDepth) maxDepth = level;
traverse(root.left, level + 1);
traverse(root.right, level + 1);
}
traverse(root, 1);
return maxDepth;
};
111.二叉树的最小深度
function minDepth(root: TreeNode | null): number {
if(!root) return 0;
let minDepth = Infinity;
function traverse(root: TreeNode | null, level: number){
if(!root) return;
if(!root.left && !root.right){
minDepth = minDepth > level ? level : minDepth;
}
traverse(root.left, level + 1);
traverse(root.right, level + 1);
}
traverse(root, 1);
return minDepth;
};