102. 二叉树的层序遍历
思路
层序遍历用队列结构实现
var levelOrder = function(root) {
let queue = [root]
let res = []
if(root == null) return res
while(queue.length){
let size = queue.length //记录上一层的size
let que = [] //每一层[]
for(let i=0; i<size; i++){
let node = queue.shift()
que.push(node.val)
if(node.left) queue.push(node.left)
if(node.right) queue.push(node.right)
}
res.push(que)
}
return res
};
226. 翻转二叉树
题目链接)
要求:给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。
思路
1.迭代法
var invertTree = function(root) {
let stack = []
if(root == null) return root
stack.push(root)
while(stack.length){
let node = stack.pop()
swap(node)
if(node.right) stack.push(node.right)
if(node.left) stack.push(node.left)
}
return root
function swap(root){ //节点交换函数,不仅仅交换数值,还需要修改指针方向
let tmp = root.left;
root.left = root.right;
root.right = tmp;
}
};
2.递归法
var invertTree = function(root) {
if(root == null) return root
swap(root)
invertTree(root.left)
invertTree(root.right)
return root
function swap(root){ //节点交换函数,不仅仅交换数值,还需要修改指针方向
let tmp = root.left;
root.left = root.right;
root.right = tmp;
}
};
- 层序遍历
var invertTree = function(root) {
let queue = [root]
if(root == null) return root
while(queue.length){
let size = queue.length
for(let i=0; i<size; i++){
let node = queue.shift()
swap(node) //这里加上交换节点的逻辑
if(node.left) queue.push(node.left)
if(node.right) queue.push(node.right)
}
}
return root
function swap(root){
let tmp = root.left;
root.left = root.right;
root.right = tmp;
}
};
101. 对称二叉树
思路
对称二叉树考虑终止条件时,有四种情况
- 左节点为空,右节点不为空,不对称,return false
- 左不为空,右为空,不对称 return false
- 左右都为空,对称,返回true
此时已经排除掉了节点为空的情况,那么剩下的就是左右节点不为空:
- 左右都不为空,比较节点数值,不相同就return false
- 左右节点都不为空,且数值相同的情况。--->进入递归
而在递归中,比较的不是左右节点,而是内侧和外侧的节点。
var isSymmetric = function(root) {
function compare(left, right){
if(left == null &&right != null) return false
else if(left != null && right == null) return false
else if(left == null && right == null) return true
else if(left.val != right.val) return false
let outside = compare(left.left, right.right)
let inside = compare(left.right, right.left)
return inside && outside
}
if(root == null) return true
return compare(root.left, root.right)
};