二叉树整理

/*
* 分别用递归和非递归方式实现二叉树先序、中序和后序遍历 【题目】 用递归和非递归方式,分别按照二叉树先序、中序和后序打印所有的节点。
* 我们约定:先序遍历顺序为根、左、右;中序遍历顺序为左、根、右;后序遍历顺序为左、右、根。
*/
二叉树样例:
这里写图片描述
递归的过程:
1 2 4 4 4 2 5 5 5 2 1 3 6 6 6 3 7 7 7 3 1
由上可知每个节点访问3次

二叉树的3个遍历:
先序: 1 2 4 5 3 6 7
中序: 4 2 5 1 6 3 7
后序: 4 5 2 6 7 3 1

创建二叉树的相应节点:

public static class Node {
        public int value;
        public Node left;
        public Node right;

        public Node(int data) {
            this.value = data;
        }
    }

递归代码如下:

先序遍历:

public static void preOrderRecur(Node head){
        if(head == null){
            return;
        }
        System.out .print(head.value + "");
        preOrderRecur(head.left);
        preOrderRecur(head.right);
    }

中序遍历:

public static void inOrderRecur(Node head) {
        if(head == null){
            return;
        }
        inOrderRecur(head.left);
        System.out .print(head.value + "");
        inOrderRecur(head.right);
    }

后序遍历:

public static void posOrderRecur(Node head) {
        if(head == null){
            return;
        }
        posOrderRecur(head.left);
        posOrderRecur(head.right);
        System.out .print(head.value + "");
    }

以下为非递归的详细讲解:
先序(根左右):有右节点先压右然后在压左节点
一下是思路模拟:

这里写图片描述

public static void preOrderUnRecur(Node head){
        System.out.print("pre-order: ");
        if(head != null){
            Stack<Node> stack = new Stack<Node>();
            stack.add(head);
            while(!stack.isEmpty()){
                head = stack.pop();
                System.out.print(head.value + " ");
                if(head.right != null){
                    stack.push(head.right);
                }
                if(head.left != null){
                    stack.push(head.left);
                }
            }
        }
        System.out.println();
    }

中序遍历(左根右):当前节点为空从栈拿一个打印当前节点往右跑,若当前节点不为空入栈当前节点往左
模拟如下:

这里写图片描述

public static void inOrderUnRecur(Node head){
        System.out.print("in-order: ");
        if(head != null){
            Stack<Node> stack = new Stack<Node>();
            while(!stack.isEmpty() || head != null){
                if(head != null){
                    stack.push(head);
                    head = head.left;
                }else {
                    head = stack.pop();
                    System.out.print(head.value + " ");
                    head = head.right;
                }
            }
        }
        System.out.println();
    }

后序遍历:
先序遍历是中左右 先压右孩子在压左孩子,那么我们想实现中左右的遍历我们仅需先压左后压右,后序遍历是左右中那么我们仅需要在利用一个栈把中右左存进去。

public static void posOrderUnRecur1(Node head) {
        System.out.print("pos-order: ");
        if(head != null){
            Stack<Node> s1 = new Stack<Node>();
            Stack<Node> s2 = new Stack<Node>();
            s1.push(head);
            while(!s1.isEmpty()){
                head = s1.pop();
                s2.push(head);
                if(head.left != null){
                    s1.push(head.left);
                }
                if(head.right != null){
                    s1.push(head.right);
                }
            }
            while (!s2.isEmpty()) {
                System.out.print(s2.pop().value + " ");

            }
        }
        System.out.println();
    }

总体代码:

package basic_class_01;

import java.util.Stack;

/*
 * 分别用递归和非递归方式实现二叉树先序、中序和后序遍历 【题目】 用递归和非递归方式,分别按照二叉树先序、中序和后序打印所有的节点。
 * 我们约定:先序遍历顺序为根、左、右;中序遍历顺序为左、根、右;后序遍历顺序为左、右、根。
 */
public class PreInPosTraversal {
    public static class Node {
        public int value;
        public Node left;
        public Node right;

        public Node(int data) {
            this.value = data;
        }
    }
    public static void preOrderRecur(Node head){
        if(head == null){
            return;
        }
        System.out .print(head.value + "");
        preOrderRecur(head.left);
        preOrderRecur(head.right);
    }
    public static void inOrderRecur(Node head) {
        if(head == null){
            return;
        }
        inOrderRecur(head.left);
        System.out .print(head.value + "");
        inOrderRecur(head.right);
    }
    public static void posOrderRecur(Node head) {
        if(head == null){
            return;
        }
        posOrderRecur(head.left);
        posOrderRecur(head.right);
        System.out .print(head.value + "");
    }

    public static void preOrderUnRecur(Node head){
        System.out.print("pre-order: ");
        if(head != null){
            Stack<Node> stack = new Stack<Node>();
            stack.add(head);
            while(!stack.isEmpty()){
                head = stack.pop();
                System.out.print(head.value + " ");
                if(head.right != null){
                    stack.push(head.right);
                }
                if(head.left != null){
                    stack.push(head.left);
                }
            }
        }
        System.out.println();
    }

    public static void inOrderUnRecur(Node head){
        System.out.print("in-order: ");
        if(head != null){
            Stack<Node> stack = new Stack<Node>();
            while(!stack.isEmpty() || head != null){
                if(head != null){
                    stack.push(head);
                    head = head.left;
                }else {
                    head = stack.pop();
                    System.out.print(head.value + " ");
                    head = head.right;
                }
            }
        }
        System.out.println();
    }
    public static void posOrderUnRecur1(Node head) {
        System.out.print("pos-order: ");
        if(head != null){
            Stack<Node> s1 = new Stack<Node>();
            Stack<Node> s2 = new Stack<Node>();
            s1.push(head);
            while(!s1.isEmpty()){
                head = s1.pop();
                s2.push(head);
                if(head.left != null){
                    s1.push(head.left);
                }
                if(head.right != null){
                    s1.push(head.right);
                }
            }
            while (!s2.isEmpty()) {
                System.out.print(s2.pop().value + " ");

            }
        }
        System.out.println();
    }

    public static void posOrderUnRecur2(Node h) {
        System.out.print("pos-order: ");
        if (h != null) {
            Stack<Node> stack = new Stack<Node>();
            stack.push(h);
            Node c = null;
            while (!stack.isEmpty()) {
                c = stack.peek();
                if (c.left != null && h != c.left && h != c.right) {
                    stack.push(c.left);
                } else if (c.right != null && h != c.right) {
                    stack.push(c.right);
                } else {
                    System.out.print(stack.pop().value + " ");
                    h = c;
                }
            }
        }
        System.out.println();
    }





    public static void main(String[] args) {
        Node head = new Node(5);
        head.left = new Node(3);
        head.right = new Node(8);
        head.left.left = new Node(2);
        head.left.right = new Node(4);
        head.left.left.left = new Node(1);
        head.right.left = new Node(7);
        head.right.left.left = new Node(6);
        head.right.right = new Node(10);
        head.right.right.left = new Node(9);
        head.right.right.right = new Node(11);


        // recursive
        System.out.println("==============recursive==============");
        System.out.print("pre-order: ");
        preOrderRecur(head);
        System.out.println();
        System.out.print("in-order: ");
        inOrderRecur(head);
        System.out.println();
        System.out.print("pos-order: ");
        posOrderRecur(head);
        System.out.println();

        // unrecursive
        System.out.println("============unrecursive=============");
        preOrderUnRecur(head);
        inOrderUnRecur(head);
        posOrderUnRecur1(head);
        posOrderUnRecur2(head);
    }

}
实验效果:

这里写图片描述

1. 最大堆 【问题描述】 堆在实际应用中有非常重要的作用,例如优先队列和堆排序。 堆实际上也是一个完全二叉树,而完全二叉树可以使用一个一维数组来保存,如下图a所示,对于一个具有n个节点的堆(完全二叉树), 其顶点按照从上而下从左至右的顺序排列保存到数组中,下标为i=0、1、2、...、n-1。 微信图片_20240402100829.jpg 很显然,对于数组下标为k的元素(顶点),其子节点的下标分别为2k+1和2k+2,其父节点的下标为(k-1)/2。 对于输入的一组数据,可以将其视为一个完全二叉树的顶点,以下代码将会将该二叉树整理为一个最大堆,同时也实现了向堆中插入元素的代码。 请将相关代码补充完整,可参考教材115页有关的代码。 其中类方法shiftdown用于实现对当前位置的元素向下递推,insertElem实现向堆中插入新的节点。 【输入形式】 输入的第一行为一个整数n,表示最开始时创建的完全二叉树顶点元素的个数 接下来的一行为n个整数,表示最开始时创建的完全二叉树顶点元素,其顺序为从上而下从左至右 接下来的一行为一个整数,表示向创建的最大堆中插入的新元素。 【输出形式】 输出为两行,第一行n个数,表示创建的最大堆的顶点值,其顺序为从上而下从左至右, 第二行n+1个数,表示最大堆中插入元素后的顶点值,其顺序为从上而下从左至右 【例输入】 10 20 12 35 15 10 80 30 17 2 1 75 【例输出】 80 17 35 15 10 20 30 12 2 1 80 75 35 15 17 20 30 12 2 1 10 【例说明】 【评分标准】 C++ (current) #include <bits/stdc++.h> using namespace std; class heap { private: int n; int *elem; void shiftdown(int pos) {
04-13
<think>嗯,用户想用C++实现最大堆,特别是shiftdown和insertElem方法。首先,我得回顾一下最大堆的定义。最大堆是一个完全二叉树,每个父节点的值都大于或等于其子节点的值。通常用数组来存储,这可以利用索引关系来找到父节点和子节点。 接下来,用户提到需要将一组数据整理成最大堆,并支持插入新元素。根据引用[1]中的Heapify方法,构造堆的时候不需要逐个插入,而是从最后一个非叶子节点开始,逐个进行shiftdown操作。这可以减少时间复杂度,从O(n log n)降到O(n)。所以在代码中,构造函数应该接收数组,然后进行Heapify处理。 然后,shiftdown方法的实现是关键。shiftdown的作用是将一个元素向下调整,直到满足最大堆的性质。具体来说,比较当前节点与其左右子节点,找到最大的那个,如果当前节点不是最大的,就交换它们,并继续向下调整。这个过程需要循环处理,直到节点到达正确的位置。引用[4]中的测试用例可能涉及这个方法,需要确保它能正确处理各种情况。 关于insertElem方法,插入元素时,应该将新元素放在数组末尾,然后向上调整(shiftup)。不过用户提到的是insertElem,可能是指插入元素后的调整过程。不过根据常规实现,插入元素后需要执行shiftup操作,而不是shiftdown。但用户特别提到要补充shiftdown和insertElem,可能需要确认。不过根据问题描述,用户可能希望将元素插入到堆中,并维护堆的性质,所以insertElem应该是将元素添加到数组末尾,然后进行shiftup调整。但根据引用[1]中的insert方法,可能用户希望的是用shiftdown?或者可能用户有混淆。需要仔细看问题。 用户的问题中明确提到“特别是shiftdown和insertElem方法的补充实现”,并解决如何整理数据为最大堆和插入元素。可能insertElem方法内部可能需要调用shiftup,而构造堆时用的是shiftdown。比如,当插入元素时,添加到末尾,然后进行shiftup操作,即比较父节点,如果更大就交换,直到根节点。而构造堆的时候,从非叶子节点开始shiftdown。 所以,在代码中,insertElem方法应该是将新元素放在数组末尾,然后执行shiftup操作。而shiftdown用于构造堆和提取元素后的调整。例如,在堆排序中,每次取出最大值后,将最后一个元素移到根节点,然后执行shiftdown。 不过根据引用[1]中的代码,maxHeap的构造函数使用shiftdown来进行Heapify。因此,在实现中,insert方法可能使用shiftup,而构造时使用shiftdown。因此,用户需要的insertElem方法可能对应的是insert操作,内部使用shiftup,而构造时使用shiftdown。 现在需要具体写这两个方法的代码。例如,shiftdown方法的参数可能是当前节点的索引,然后循环比较子节点,进行交换。insertElem则是将元素添加到数组末尾,然后执行shiftup,即比较父节点,直到根节点。 此外,数组的索引通常从1开始,这计算父节点和子节点的索引更方便。例如,父节点索引为i/2,左子节点为2i,右子节点为2i+1。但有时也会从0开始,这需要统一。根据引用[1]中的构造函数,data数组是从索引1开始存储元素的,所以代码中需要注意这一点。 在代码实现中,数据存储的数组可能是一个动态数组,比如vector或者手动管理的数组。用户提到是C++实现,所以可能使用动态数组,但需要处理容量的问题。例如,insertElem时可能需要检查数组是否已满,进行扩容。 总结,最大堆的C++类应该包含以下部分: 1. 数据存储的数组,索引从1开始。 2. 构造函数,接受数组并进行Heapify(使用shiftdown)。 3. insertElem方法,添加元素到末尾并执行shiftup。 4. shiftDown方法,用于调整堆结构。 5. extractMax方法,取出最大值并调整堆。 现在需要具体实现这些部分,特别是shiftdown和insertElem。例如,shiftdown的代码逻辑可能如下: void shiftDown(int k) { while (2*k <= count) { // 有子节点 int j = 2*k; // 左子节点 if (j+1 <= count && data[j+1] > data[j]) { // 右子节点存在且更大 j++; } if (data[k] >= data[j]) break; // 当前节点大于子节点,满足条件 swap(data[k], data[j]); // 交换 k = j; // 继续向下调整 } } 而insertElem的代码逻辑可能是: void insertElem(T elem) { if (count == capacity) { // 扩容处理 // 扩大数组容量 } data[++count] = elem; // 添加到末尾 shiftUp(count); // 向上调整 } void shiftUp(int k) { while (k > 1 && data[k/2] < data[k]) { // 父节点小于当前节点 swap(data[k/2], data[k]); k = k/2; } } 但用户的问题中重点在于shiftdown和insertElem,所以可能需要确保这些方法的正确性。根据引用[1]中的构造函数,Heapify过程是从count/2的位置开始,逐个shiftdown,这可能也是正确的。 现在,将这些思路整合成代码,并给出示例,比如如何构造堆和插入元素。同时,需要处理数组的容量问题,比如在插入时动态扩容。例如,使用vector或者动态数组管理。 此外,用户提供的引用[4]中的测试用例可能对验证代码正确性有帮助,可以引用这些测试来确保实现正确。</think>以下为C++实现最大堆的完整代码,包含`shiftDown`和`insertElem`方法的具体逻辑,并附带构建最大堆和插入元素的操作说明: --- ### 最大堆的C++实现 ```cpp #include <vector> #include <algorithm> template<typename T> class MaxHeap { private: std::vector<T> data; // 索引从1开始存储,data[0]空置 int capacity; int count; // 向下调整 void shiftDown(int k) { while (2 * k <= count) { // 存在左子节点 int j = 2 * k; // 左子节点索引 // 如果存在右子节点且右子节点更大,则选择右子节点 if (j + 1 <= count && data[j + 1] > data[j]) { j++; } // 父节点大于子节点则无需调整 if (data[k] >= data[j]) break; std::swap(data[k], data[j]); // 交换父子节点 k = j; // 继续向下调整 } } // 向上调整 void shiftUp(int k) { while (k > 1 && data[k / 2] < data[k]) { // 父节点小于当前节点 std::swap(data[k], data[k / 2]); k = k / 2; } } public: // 构造函数(Heapify方式构建堆) MaxHeap(T arr[], int n) { capacity = n; count = n; data.resize(n + 1); // 索引从1开始 for (int i = 0; i < n; i++) { data[i + 1] = arr[i]; } // 从最后一个非叶子节点开始调整 for (int k = count / 2; k >= 1; k--) { shiftDown(k); } } // 插入新元素 void insertElem(T elem) { if (count == capacity) { // 扩容处理 capacity *= 2; data.resize(capacity + 1); } data[++count] = elem; // 添加到末尾 shiftUp(count); // 向上调整 } // 提取最大值 T extractMax() { T max = data[1]; std::swap(data[1], data[count]); // 将末尾元素交换到根节点 count--; shiftDown(1); // 从根节点向下调整 return max; } }; ``` --- ### 代码逻辑解析 1. **`shiftDown`方法** - 从索引`k`开始,比较父节点与左右子节点的值 - 若父节点小于子节点,则交换两者位置,并继续向下调整 - 时间复杂度:$O(\log n)$ 2. **`insertElem`方法** - 将新元素插入到数组末尾(索引`count+1`) - 通过`shiftUp`调整新元素的位置,直到满足最大堆性质 - 时间复杂度:$O(\log n)$ 3. **Heapify构造方法** - 直接将原始数组复制到堆中,从最后一个非叶子节点(索引`count/2`)开始,依次调用`shiftDown` - 时间复杂度:$O(n)$,优于逐个插入的$O(n \log n)$[^1] --- ### 应用示例 ```cpp int main() { int arr[] = {9, 3, 7, 6, 5, 1, 8, 2, 4}; MaxHeap<int> heap(arr, 9); // 通过Heapify构造最大堆 heap.insertElem(10); // 插入新元素 while (heap.size() > 0) { // 依次提取最大值 std::cout << heap.extractMax() << " "; } // 输出:10 9 8 7 6 5 4 3 2 1 return 0; } ``` --- ### 性能优化说明 - **Heapify构造方法**通过减少元素移动次数,将建堆时间复杂度优化到$O(n)$[^1] - **动态扩容**在插入元素时自动扩展容量,避免频繁内存分配 - **`extractMax`方法**通过交换末尾元素与根节点,保持堆的完全二叉树性质[^4] --- 相关问题
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值