226.翻转二叉树
题目链接:
https://leetcode.cn/problems/invert-binary-tree/
题目描述:
给你一棵二叉树的根节点 root
,翻转这棵二叉树,并返回其根节点。
输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]
思路:
层次遍历二叉树,交换每个节点的左右子节点
代码:
var invertTree = function(root) {
let queue = []
if(root) queue.push(root)
while(queue.length){
let size = queue.length
for(let i = 0; i < size; i++){
let cur = queue.shift()
let temp = cur.left
cur.left = cur.right
cur.right = temp
cur.left && queue.push(cur.left)
cur.right && queue.push(cur.right)
}
}
return root
};
101.对称二叉树
题目链接:
https://leetcode.cn/problems/symmetric-tree/
题目描述:
给你一个二叉树的根节点 root
, 检查它是否轴对称。
输入:root = [1,2,2,3,4,4,3]
输出:true
思路:
将根节点的左右子节点加入到栈中,每次循环从栈中弹出两个进行判断,再将对称的子节点两两压入栈中。多次循环直到栈为空,表示遍历完成。
代码:
var isSymmetric = function(root) {
if(root.left && !root.right) return false
if(root.right && !root.left) return false
if(!root.left && !root.right) return true
let stack = [root.left,root.right]
while(stack.length){
let right = stack.pop()
let left = stack.pop()
if (!left && !right) {
continue;
}
if ((!left || !right || (left.val != right.val))) {
return false;
}
stack.push(left.left);
stack.push(right.right);
stack.push(left.right);
stack.push(right.left);
}
return true;
};
标签:right,cur,javascript,随想录,day15,let,root,stack,left
From: https://www.cnblogs.com/endmax/p/16966334.html