题目一 102. 二叉树的层序遍历
思路
层序遍历,借助队列,循环队列的过程中,先记录这时候队列中的元素个数,然后循环队列,出队,访问该元素,并将元素的左右子节点入队。
var levelOrder = function(root) {
if (!root) {
return []
}
let queue = [root];
let result = [];
while (queue.length) {
let arr = [];
let len = queue.length;
for (let i = 0; i < len; i++) {
const node = queue.shift();
arr.push(node.val);
if (node.left) {
queue.push(node.left);
}
if (node.right) {
queue.push(node.right);
}
}
result.push(arr);
}
return result;
};
题目二 226. 翻转二叉树
思路
递归实现翻转,将root的左孩子赋值为右子树反转的最后节点,右子树赋值为左子树翻转的结果。这里要注意的是需要先保存左节点,因为赋值执行过后,它就变了,所以要缓存一下。
var invertTree = function(root) {
if (!root) {
return root;
}
let left = root.left;
root.left = invertTree(root.right);
root.right = invertTree(left);
return root;
};
题目三 101. 对称二叉树
思路
同时比较左右两颗子树的对称节点,终止条件需要判断三种情况:
- 一个节点为空,另一个不为空,返回false
- 都为空,返回true
- 都不为空,如果元素不相等,返回false,如果相等,需要递归判断左子树和右子树是否对称。
var isSymmetric = function(root) {
if (!root) {
return true;
}
const compare = (left, right) => {
if (!left && right) {
return false;
} else if (left && !right) {
return false;
} else if (!left && !right) {
return true;
} else if (left.val !== right.val) {
return false;
}
const inside = compare(left.right, right.left);
const outside = compare(left.left, right.right);
return inside && outside;
}
return compare(root.left, root.right);
};
3个月后二刷自己写出来了,但这题在leetcode中属于简单题目,==,革命尚未成功,同志仍需努力啊。
var isSymmetric = function(root) {
if (!root) {
return true;
}
const isEqual = (left, right) => {
if (!left && !right) {
return true;
} else if ((left && !right) || (!left && right)) {
return false;
} else if (left.val !== right.val) {
return false;
}
return isEqual(left.left, right.right) && isEqual(left.right, right.left)
};
return isEqual(root.left, root.right);
}
碎碎念
好吧,第三题依然没有写出来,看了答案才明白,今天问了下今年面试情况,果然是地狱难度,感觉要终结了,😮💨