public static class TreeNode{
int val;
TreeNode left;
TreeNode right;
public TreeNode(){
this.left = this.right = null;
}
public TreeNode(int val){
this.val = val;
}
}
public static TreeNode creatHeap(int []nums){
if(nums == null || nums.length == 0){
return null;
}
TreeNode root = new TreeNode(nums[0]);
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
queue.addFirst(root);
for(int i = 1; i < nums.length; i++){
TreeNode bt = queue.pollLast();
bt.left = new TreeNode(nums[i]);
queue.addFirst(bt.left);
i++;
if(i < nums.length){
bt.right = new TreeNode(nums[i]);
queue.addFirst(bt.right);
}
root = justHeap(root);
}
return root;
}
public static TreeNode justHeap(TreeNode root){
if(root == null || (root.left == null && root.right == null)){
return root;
}
justHeap(root.left);
justHeap(root.right);
if(root.left != null){
if(root.val < root.left.val){
int tmp = root.val;
root.val = root.left.val;
root.left.val = tmp;
}
}
if(root.right != null){
if(root.val < root.right.val){
int tmp = root.val;
root.val = root.right.val;
root.right.val = tmp;
}
}
return root;
}学了个堆排序
最新推荐文章于 2024-10-27 21:30:45 发布
1151

被折叠的 条评论
为什么被折叠?



