#965. Univalued Binary Tree
用DFS来解决这个问题,如果根存在,就把节点的值放在数组中,然后继续遍历它的左右子节点。最后判断数组中元素是否都相等就可以了。相同就是独一无二的树。
function dfs(root,val) {
if(root) {
val.push(root.val);
dfs(root.left,val);
dfs(root.right,val);
}
}
var isUnivalTree = function(root) {
var val=[];
dfs(root,val);
return Array.from(new Set(val)).length===1;
};
#101. Symmetric Tree
这道题同样使用dfs,同时去比较树的左右子节点。
var isSymmetric = function(root) {
return dfs(root,root);
};
function dfs(p,q) {
if(p==null && q==null) {
return true;
}
if(p==null || q==null) {
return false;
}
return p.val==q.val && dfs(p.left,q.right) && dfs(p.right,q.left);
}
#226. Invert Binary Tree
这道题十分简单。就是树交换值的方式。
var invertTree = function(root) {
if(root !== null) {
let temp = root.left;
root.left = invertTree(root.right);
root.right = invertTree(temp)
}
return root;
};
#897. Increasing Order Search Tree
Given a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only 1 right child.
这是一道二叉树中序遍历的问题。将中序遍历得到的结果再拼成一颗左节点为null,右节点为遍历后的数组中的值的树。注意最后一个节点需要把它的左右节点都置为空。
var increasingBST = function(root) {
let arr = [];
InOrderTraversal(arr,root);
for(let i=0;i<arr.length;i++) {
if(i==arr.length-1) {
arr[i].right=null;
}
else {
arr[i].right=arr[i+1];
}
arr[i].left=null;
}
return arr[0];
};
function InOrderTraversal(arr,root) {
if(root===null) {
return;
}
InOrderTraversal(arr,root.left);
arr.push(root);
InOrderTraversal(arr,root.right);
}
#104. Maximum Depth of Binary Tree
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
用递归分别找到左子节点的最大深度和右子节点的最大深度,然后加叶子节点所在的那一层,最后得到最大的深度。
var maxDepth = function(root) {
if(!root) {
return 0;
}
let leftDepth = maxDepth(root.left);
let rightDepth = maxDepth(root.right);
return Math.max(leftDepth,rightDepth)+1;
};
#589. N-ary Tree Preorder Traversal
N叉树的先序遍历就是先遍历根节点然后遍历子节点。用一个栈来记录。先把根节点push到栈中。然后只要栈不为空就一直循环。每次pop出栈一个元素,把它的值放在结果数组中,然后把它的子节点都push到栈中,注意这里先push最后一个子节点,这样才能按照正确的顺序pop到结果数组中。最后输出这个结果数组
var preorder = function(root) {
if(!root) {
return [];
}
var result=[];
var stack=[];
stack.push(root);
while(stack.length>0) {
var node = stack.pop();
result.push(node.val);
for(var i=node.children.length-1;i>=0;i--) {
stack.push(node.children[i]);
}
}
return result;
};
#590. N-ary Tree Postorder Traversal
N叉树的后序遍历就是先遍历根节点然后遍历子节点。同样用一个栈,并将root push到栈中,当栈不为空就循环。每次pop出一个值并放在结果数组中,然后把子节点push到栈中。最后将结果数组reverse就是最后的后序遍历结果。
var postorder = function(root) {
if(!root) {
return [];
}
var result=[];
var stack=[];
stack.push(root);
while(stack.length>0) {
var node=stack.pop();
result.push(node.val);
for(var i=0;i<node.children.length;i++) {
stack.push(node.children[i])
}
}
return result.reverse();
};