代码随想录算法训练营第第15天 | 层序遍历10道题 、226.翻转二叉树 、101. 对称二叉树
层序遍历
看完本篇可以一口气刷十道题,试一试, 层序遍历并不难,大家可以很快刷了十道题。
题目链接/文章讲解/视频讲解:https://programmercarl.com/0102.二叉树的层序遍历.html
层序遍历,10道题,一一通过,比较简单
226.翻转二叉树 (优先掌握递归)
这道题目 一些做过的同学 理解的也不够深入,建议大家先看我的视频讲解,无论做过没做过,都会有很大收获。
题目链接/文章讲解/视频讲解:https://programmercarl.com/0226.翻转二叉树.html
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var invertTree = function(root) {
if (root === null) return root;
const stack = [root];
while(stack.length){
let len = stack.length;
for (let i=0;i<len;i++) {
let node = stack.shift();
let left = node.left;
node.left = node.right;
node.right = left;
node.left && stack.push(node.left);
node.right && stack.push(node.right);
}
}
return root;
};
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var invertTree = function(root) {
if (root == null) return root;
let left = root.left;
root.left = root.right;
root.right = left;
root.left && invertTree(root.left);
root.right && invertTree(root.right);
return root;
};
- 对称二叉树 (优先掌握递归)
先看视频讲解,会更容易一些。
题目链接/文章讲解/视频讲解:https://programmercarl.com/0101.对称二叉树.html
function symmetry(left, right) {
if (left ===null && right === null) {
return true;
} else if (left !== null && right === null) {
return false;
} else if (left === null && right !== null) {
return false;
} else if (left.val !== right.val) {
return false;
}
let outside = symmetry(left.left, right.right);
let inside = symmetry(left.right, right.left);
return outside && inside;
}
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/
var isSymmetric = function(root) {
if (root === null) return true;
return symmetry(root.left, root.right);
};