都不是很难 写一起算了
94. 二叉树的中序遍历
javascript
//递归
derTraversal = function(root) {
const ans=[];
var dfs=function(root){
if(!root) return ;
if(root.left) dfs(root.left);
ans.push(root.val);
dfs(root.right);
}
dfs(root);
return ans;
};
//迭代
var inorderTraversal = function(root) {
const ans=[];
const stack=[];
while(root||stack.length){
while(root){
stack.push(root);
root=root.left;
}
if(stack.length){
root=stack.pop();
ans.push(root.val);
root=root.right;
}
}
return ans;
};
104. 二叉树的最大深度
javascript
axDepth = function(root) {
if(!root) return 0;
const leftroot=maxDepth(root.left)+1;
const rightroot=maxDepth(root.right)+1;
return leftroot>=rightroot?leftroot:rightroot;
};
226. 翻转二叉树
javascript
var invertTree = function(root) {
if(root){
[root.right,root.left]=[root.left,root.right];
invertTree(root.left);
invertTree(root.right);
}
return root;
};
101. 对称二叉树
javascript
var isSymmetric = function(root) {
if(!root) return true;
var dfs=function(node1,node2){
if(!node1&&!node2) return true;
if(!node1||!node2) return false;
if(node1.val!=node2.val) return false;
return dfs(node1.left,node2.right)&&
dfs(node1.right,node2.left);
};
return dfs(root.left,root.right);
};
//简洁写法(灵神)
var isSymmetric = function(root) {
function isSameTree(p, q) {
if (p === null || q === null) {
return p === q;
}
return p.val === q.val && isSameTree(p.left, q.right) && isSameTree(p.right, q.left);
}
return isSameTree(root.left, root.right);
};