二叉树经典例题

二叉树:

    static class Node {
        private int data;
        private Node left;
        private Node right;

        public Node() {

        }

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

        public int getData() {
            return data;
        }

        public void setData(int data) {
            this.data = data;
        }

        public Node getLeft() {
            return left;
        }

        public void setLeft(Node left) {
            this.left = left;
        }

        public Node getRight() {
            return right;
        }

        public void setRight(Node right) {
            this.right = right;
        }

1、分别先序、中序、后序遍历二叉树

递归:

思路:注意与打印位置的关系

先序:

    public static void method(Node node) {
        if (node == null) {
            return;
        }
        System.out.println(node.data);
        method(node.left);
        method(node.right);
    }

中序:

    public static void method(Node node) {
        if (node == null) {
            return;
        }
        method(node.left);
        System.out.println(node.data);
        method(node.right);
    }

后序:

    public static void method(Node node) {
        if (node == null) {
            return;
        }
        method(node.left);
        method(node.right);
        System.out.println(node.data);
    }

非递归:

先序:

思路:通过栈,当前节点的右节点压栈,输出当前节点,当前指向左节点。左边为空时出栈

    public static void method(Node head) {
        if (head == null) {
            return;
        }
        Stack stack = new Stack();
        Node node = head;

        while (node != null || stack.size() != 0) {
            if (node == null) {
                node = (Node) stack.pop();
            }

            System.out.println(node.data);
            if (node.right != null) {
                stack.add(node.right);
            }

            node = node.left;
        }

    }

中序:

思路:将左节点全部压入栈中,弹出时指向弹出节点的右节点

如果当前节点的左节点不为空,压入栈中,且当前节点指向左节点。

为空的话,指向栈中弹出节点,输出当前节点,并指向当前节点的右节点。

    public static void method(Node head) {
        if (head == null) {
            return;
        }
        Stack stack = new Stack();
        Node node = head;

        while (node != null || stack.size() != 0) {
            if (node != null) {
                stack.add(node);
                node = node.left;
            } else {
                node = (Node) stack.pop();
                System.out.println(node.data);
                node = node.right;
            }

        }

    }

后序:

思路:后序的顺序是 “ 左右中”, 反转过来也就是 “ 中左右” 与先序类似,所以方法就是先用类似先序的方法 以 “ 中左右” 的顺序压入栈中,再用另一个栈反转。

    public static void method(Node head) {
        if (head == null) {
            return;
        }
        Node node = head;
        Stack<Node> stack = new Stack();
        Stack<Node> result = new Stack();
        while (node != null || stack.size() != 0) {
            if (node == null) {
                node = stack.pop();
            }

            result.add(node);

            if (node.left != null) {
                stack.add(node.left);
            }
            node = node.right;
        }

        while (result.size() != 0) {
            System.out.println(result.pop().data);
        }
    }

2、按层遍历二叉树。

思路:

输出当前节点,并将当前节点的左右节点都放入队列中

    public static void method(Node head) {
        Queue<Node> queue = new ArrayBlockingQueue<>(100);
        Node node = head;
        while (queue.size() != 0 || node != null) {
            System.out.println(node.getData());
            if (node.left != null) {
                queue.add(node.left);
            }
            if (node.right != null) {
                queue.add(node.right);
            }

            node = queue.poll();
        }

    }

 

3、求一个节点的后继(中序遍历时,当前节点的下一个节点)。二叉树结构如下:有一个parent指针指向父节点。

public class Node { 
    public int value; 
    public Node left;
    public Node right;
    public Node parent;
public Node(int data) { this.value = data; }
}

思路: 

1、当前节点有右节点的话,后继就是当前节点右子树的最左节点

2、否则的话,就找当前子树是左子树(不是的话继续向上找)的父节点

    public static Node method(Node head) {
        Node node = head;
//        返回右子树的最左子树
        if (node.right != null) {
            node = node.right;
            while (node.left != null) {
                node = node.left;
            }
            return node;
        }
//        返回当前子树为左子树的父节点
        while (node.parent != null) {
            if (node == node.parent.left) {
                return node.parent;
            }
            node = node.parent;
        }
        return null;
    }

4、二叉树的序列化和反序列化。

(1)先序:

非递归 先序 序列化

思路:类比先序遍历。

    public static String method(Node head) {
        StringBuilder stringBuilder = new StringBuilder();
        Node node = head;
        Stack<Node> stack = new Stack<>();
        while (stack.size() != 0 || node != null) {
            if (node == null) {
                stringBuilder.append("null_");
                node = stack.pop();
            }
            stringBuilder.append(node.getData() + "_");
            if (node.right != null) {
                stack.add(node.right);
            } else {
                stringBuilder.append("null_");
            }
            node = node.left;
        }
        return stringBuilder.toString();
    }
1_2_4_null_null_5_8_null_null_9_null_null_3_6_null_null_7_null_

递归 先序 序列化

    public static String method2(Node node) {

        StringBuilder stringBuilder = new StringBuilder();

        if (node == null) {
            return "null_";
        }

        stringBuilder.append(node.getData() + "_");
        stringBuilder.append(method2(node.left));
        stringBuilder.append(method2(node.right));
        return stringBuilder.toString();
    }

递归 先序 反序列化

思路:类似于遍历。

    public static Node method(String string) {
        Queue<String> queue = new LinkedList<>();
        String[] splits = string.split("_");
        for (String split : splits) {
            queue.add(split);
        }
        return method4(queue);
    }

    public static Node method4(Queue<String> queue) {

        if (queue.peek().equals("null")) {
            queue.poll();
            return null;
        }

        Node node = new Node(Integer.parseInt(queue.poll()));
        node.left = method4(queue);
        node.right = method4(queue);
        return node;
    }

------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 

(2)分层 

非递归 按层 序列化

思路:遍历。

    public static String method4(Node head) {
        Node node = head;
        StringBuilder stringBuilder = new StringBuilder();
        Queue<Node> queue = new LinkedList<>();
        if (node != null) {
            stringBuilder.append(node.data + "_");
            queue.add(node);
        } else {
            stringBuilder.append("null_");
        }

        while (!queue.isEmpty()) {
            node = queue.poll();
            if (node.left != null) {
                queue.add(node.left);
                stringBuilder.append(node.left.data + "_");
            }else {
                stringBuilder.append("null_");
            }

            if (node.right != null) {
                queue.add(node.right);
                stringBuilder.append(node.right.data + "_");
            } else {
                stringBuilder.append("null_");
            }

        }
        return stringBuilder.toString();
    }

非递归 按层 反序列化

    public static Node method(String string) {
        String[] splits = string.split("_");
        Queue<Node> nodeQueue = new LinkedList<>();
        Node node;
        int index = 0;

        node = helpMethod(splits[index++]);
        Node head = node;
        if (node != null) {
            nodeQueue.offer(node);
        }

        while (!nodeQueue.isEmpty()) {
            node = nodeQueue.poll();

            node.left = helpMethod(splits[index++]);
            node.right = helpMethod(splits[index++]);
            if (node.left != null) {
                nodeQueue.offer(node.left);
            }

            if (node.right != null) {
                nodeQueue.offer(node.right);
            }
        }
        return head;

    }

5、判断是否为平衡二叉树。

平衡二叉树:每个节点的左右子树高度相差不大于1(<= 1)。

思路:递归,每深入一层,当前高度加1,左右子树高度差 <= 1 时,返回高的子树高度,否则返回-1.

    public static boolean method(Node head) {
        Node node = head;
        int balance = isBalance(node, 1);
        if (balance != -1) {
            return true;
        }
        return false;
    }

    public static int isBalance(Node head, int level) {
        Node node = head;
        if (node == null) {
            return level - 1;
        }
        int leftHeight = isBalance(node.left, level+1);
        int rightHeight = isBalance(node.right, level+1);
        if (Math.abs(leftHeight - rightHeight) <= 1) {
            return Math.max(leftHeight, rightHeight);
        } else {
            return -1;
        }
    }

6、判断是否为搜索二叉树(中序遍历有序)

思路1:中序遍历一遍,再看是否有序

    public static boolean method(Node head) {
        Node node = head;
        Queue<Integer> queue = new LinkedList<>();
        method1(node, queue);
        int temp = queue.poll();
        for (Integer integer : queue) {
            if (integer < temp) {
                return false;
            }
            temp = integer;
        }
        return true;
    }

    public static Queue<Integer> method1(Node head, Queue<Integer> queue) {
        Node node = head;
        if (node == null) {
            return null;
        }
        method1(node.left, queue);
        queue.add(node.data);
        method1(node.right, queue);
        return queue;
    }

思路2、根据非递归中序遍历,遍历时看当前数是否大于等于上一个数。

    public static boolean method(Node head) {
        Node node = head;
        Stack<Node> stack = new Stack<>();
        while (node.left != null) {
            node = node.left;
        }
        int temp = node.data;
        node = head;

        while (!stack.isEmpty() || node != null) {
            if (node == null) {
                node = stack.pop();
                if (node.data >= temp) {
                    temp = node.data;
                } else {
                    return false;
                }
                node = node.right;
            }
            if (node != null) {
                stack.add(node);
                node = node.left;
            }
        }
        return true;
    }

7、判断一棵树是否为完全二叉树(叶子节点从左向右)

思路:分层遍历,记一个标记 isleaf ,如果当前节点为叶子节点, 之后的节点就不能有子树

    public static boolean method(Node head) {
        Queue<Node> queue = new LinkedList<>();
        Node node = head;
        Boolean isLeaf = false;
        if (node != null) {
            queue.add(node);
        }

        while (!queue.isEmpty()) {

            node = queue.poll();
            if (node.left != null) {
                if (isLeaf == true) {
                    return false;
                }
                queue.add(node.left);
            } else {
                isLeaf = true;
            }

            if (node.right != null) {
                if (isLeaf == true) {
                    return false;
                }
                queue.add(node.right);
            }else {
                isLeaf = true;
            }
        }

        return true;
    }

8、求一棵完全二叉树的节点个数。要求时间复杂度小于O(n)。

思路:当前节点右子树最左节点如果存在的话,左子树就是满二叉树。

否则,右子树就是满二叉树。

满二叉树很容易算,然后再看不满的那一边

时间复杂度为(logn)^2 ,因为每次都是按层数遍历一遍

    public static int getNumber(Node head) {
        return getNumber(head, 1, getHeight(head));
    }
    /**
     * @param node
     * @param level 当前节点所在层数
     * @param height 最大的所求完全二叉树的高度(不变)
     * @return
     */
    public static int getNumber(Node node, int level, int height) {
        int num = 0;
        if (node == null) {
            return 0;
        }
//        当前树右子树的最左节点存在
        if (getHeight(node.right) + level == height) {
//            左子树为满二叉树
            num += (int) Math.pow(2, height - level);
//            右子树重复当前过程
            num += getNumber(node.right, level + 1, height);
        } else {
            num += Math.pow(2, getHeight(node.right));
            num += getNumber(node.left, level + 1, height);
        }
        return num;
    }

    /**
     * 获取当前完全二叉树的高度(最左节点的高度)
     * @param head
     * @return
     */
    public static int getHeight(Node head) {
        Node node = head;
        int height = 0;
        while (node != null) {
            height++;
            node = node.left;
        }
        return height;
    }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: "数据结构经典例题名家代码"是一本经典的数据结构教材,其中包含了许多著名数据结构例题和相关的代码实现。 书中介绍了各种常见的数据结构,如线性结构(数组、链表、栈、队列)、树结构(二叉树、堆、哈夫曼树)、图结构(邻接矩阵、邻接表)等。每个数据结构都有详细的介绍和示例代码,可以帮助读者理解和掌握这些数据结构的基本原理和操作。 除了介绍数据结构的基本知识之外,书中还包含了许多算法和问题的实际应用。比如,如何使用数据结构解决迷宫问题、查找算法、排序算法等。这些例题和代码展示了数据结构在实际问题中的应用和灵活性,有助于读者培养解决问题的思维方式和能力。 作者通过清晰的讲解和简洁的代码示例,使得读者可以更好地理解和掌握数据结构的基本原理和使用方法。书中还附带了一些习题和答案,供读者巩固知识和提升编程能力。 综上所述,"数据结构经典例题名家代码"是一本非常适合学习和了解数据结构的经典教材,它通过丰富的例题和相关代码,帮助读者深入理解和掌握数据结构的概念和应用。无论是初学者还是有一定基础的人员,都可以从中受益。 ### 回答2: 经典例题名家代码之一是二叉树的遍历问题。二叉树是一种重要的数据结构,其遍历方式有三种:前序遍历、中序遍历和后序遍历。 前序遍历就是按照“根左右”的顺序访问二叉树的节点。中序遍历按照“左根右”的顺序进行访问,而后序遍历则是按照“左右根”的顺序进行访问。 以前序遍历为例,我们可以使用递归方法来实现。首先遍历根节点,然后递归地遍历左子树,最后递归地遍历右子树。这种递归思想可以通过以下代码实现: ```python class Node: def __init__(self, data): self.data = data self.left = None self.right = None def preorder_traversal(root): if root: print(root.data) preorder_traversal(root.left) preorder_traversal(root.right) # 示例二叉树 # 1 # / \ # 2 3 # / \ \ # 4 5 6 root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.right = Node(6) preorder_traversal(root) # 输出: 1 2 4 5 3 6 ``` 以上代码通过定义一个`Node`类来构造二叉树,并使用递归函数`preorder_traversal()`来进行前序遍历。输出结果为`1 2 4 5 3 6`,表示了二叉树的先序遍历结果。 通过这个经典例题和代码,我们可以理解并掌握二叉树的遍历方式,深入理解数据结构的基本原理和常见操作。这些都是学习和理解数据结构的重要一步。 ### 回答3: 经典例题名家代码中,常见的一个例子是快速排序算法。快速排序算法是一种高效的排序算法,其核心思想是通过将待排序的序列划分为较小和较大的两个子序列,然后递归地对这两个子序列进行排序,最终实现整个序列的有序。 快速排序算法的名家代码主要体现在该算法的划分过程和递归思想上。其中,划分过程的关键是选择一个基准元素,并通过交换元素的位置,将小于基准元素的元素移到基准元素的左边,将大于基准元素的元素移到基准元素的右边。而递归思想则是对划分后的子序列进行递归调用,直到子序列只有一个元素或为空。 以下是一种经典的快速排序算法的代码示例: ``` void quickSort(int[] arr, int left, int right) { if (left < right) { int pivotIndex = partition(arr, left, right); // 获取基准元素的位置 quickSort(arr, left, pivotIndex - 1); // 对基准元素左边的子序列进行排序 quickSort(arr, pivotIndex + 1, right); // 对基准元素右边的子序列进行排序 } } int partition(int[] arr, int left, int right) { int pivot = arr[left]; // 选择第一个元素作为基准元素 int i = left, j = right; while (i < j) { while (i < j && arr[j] >= pivot) { j--; } if (i < j) { arr[i++] = arr[j]; } while (i < j && arr[i] <= pivot) { i++; } if (i < j) { arr[j--] = arr[i]; } } arr[i] = pivot; return i; } ``` 以上是一个典型的快速排序算法的代码实现,通过划分和递归的方式,能够高效地对一个序列进行排序。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值