108. 将有序数组转换为二叉搜索树
104. 二叉树的最大深度
105. 从前序与中序遍历序列构造二叉树
108. 将有序数组转换为二叉搜索树
给你一个整数数组 nums ,其中元素已经按 升序 排列,请你将其转换为一棵 高度平衡 二叉搜索树。
高度平衡 二叉树是一棵满足「每个节点的左右两个子树的高度差的绝对值不超过 1 」的二叉树。
class Solution {
private TreeNode buildTree(int[] nums,int left,int right){
if(left>right)
return null;
int mid=(left+right)/2;
TreeNode root=new TreeNode(nums[mid]);
root.left=buildTree(nums,left,mid-1);
root.right=buildTree(nums,mid+1,right);
return root;
}
public TreeNode sortedArrayToBST(int[] nums) {
return buildTree(nums,0,nums.length-1);
}
}
104. 二叉树的最大深度
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
class Solution {
private int getMaxDepth(TreeNode root){
if(root==null)
return 0;
int left=getMaxDepth(root.left);
int right=getMaxDepth(root.right);
return Math.max(left,right)+1;
}
public int maxDepth(TreeNode root) {
return getMaxDepth(root);
}
}
105. 从前序与中序遍历序列构造二叉树
根据一棵树的前序遍历与中序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出前序遍历 preorder = [3,9,20,15,7] 中序遍历 inorder = [9,3,15,20,7]
class Solution {
private Map<Integer,Integer> map=new HashMap<>();
private TreeNode mybuildTree(int[] preorder,int[] inorder,int preleft,int preright,int inleft,int inright){
if(preleft>preright)
return null;
TreeNode root=new TreeNode(preorder[preleft]);
int inindex=map.get(root.val);
root.left=mybuildTree(preorder,inorder,preleft+1,inindex-inleft+preleft,inleft,inindex);
root.right=mybuildTree(preorder,inorder,inindex-inleft+preleft+1,preright,inindex+1,inright);
return root;
}
public TreeNode buildTree(int[] preorder, int[] inorder) {
for(int i=0;i<inorder.length;i++){
map.put(inorder[i],i);
}
return mybuildTree(preorder,inorder,0,preorder.length-1,0,inorder.length-1);
}
}