101 对称二叉树
在最开始做这道的时候,我的dfs只拿了一个node作为参数,然后比较node的左子节点和右子节点,但是对于这种比较两节点的题,使用left和right两个参数作为dfs更好。
var isSymmetric = function(root) {
if (!root) {
return true
}
const dfs = (left, right) => {
if (left === null && right === null) {
return true
}
if (left === null || right === null) {
return false
}
if (left.val !== right.val) {
return false
}
return dfs(left.left, right.right) && dfs(left.right, right.left)
}
return dfs(root.left, root.right)
};
226 翻转二叉树
先翻转左子树,再翻转右子树,之后把左子树作为root的右子树,右子树作为root的左子树,实现翻转。
var invertTree = function(root) {
if (!root) return root
const left = invertTree(root.left)
const right = invertTree(root.right)
root.left = right
root.right = left
return root
};