Leetcode 与树(TreeNode )相关的题解测试工具函数总结

LeetCode收录了许多互联网公司的算法题目,被称为刷题神器。最近在剑指Offer上也刷了一些题目,发现涉及到数据结构类的题目,比如说“树”、“链表"这种题目,如果想在本地IDE进行测试,除了完成题目要求的算法外,还需要写一些辅助函数,比如树的创建,遍历等,由于这些函数平时用到的地方比较多,并且也能加深对常用数据结构的理解,这里将Leetcode中与树(TreeNode)相关题目会用到的测试辅助函数做一个总结。

代码文件说明

  1. LeetCode 剑指Offer在线编程中关于树的数据结构定义
  2. TreeHelper.java: 主要是和树相关的常用操作函数,包括:二叉树的创建、三种遍历、获取树的节点数,高度、判断是否为二叉搜索树,以及搜索二叉树的创建、插入、删除
  3. TreeHelperTest.java: 主要用来对TreeHelper.java中的函数进行测试
  4. Solution18:LeetCode 剑指Offer在线编程第18道题"二叉树的镜像"题解,和本地测试方法

源代码

1.TreeNode.java

package structure;

public class TreeNode {
  public int val = 0;
  public TreeNode left = null;
  public TreeNode right = null;

  public TreeNode(int val) {
    this.val = val;
  }

}

2.TreeHelper.java

package structure;
import static java.lang.Math.max;

public class TreeHelper {

    static int index;
    static String[] values;

    public TreeHelper(){}

    // 根据形如”1,2,#,4,5,#,7,#“的字符串建立二叉树,其中#代表该节点为空
    public void setValues(String treeValues) {
        values = treeValues.split(",");
        index = 0;

    }

    // 递归建立二叉树
    public TreeNode createTree() {
        TreeNode node = null;
        if(index < values.length){
            if (values[index].equals("#")) {
                index++;
                return null;
            }
            node = new TreeNode(Integer.parseInt(values[index]));
            index++;
            node.left = createTree();
            node.right = createTree();
        }
        return node;
    }

    //前序遍历
    public void preOrder(TreeNode root) {
        if (root == null) {
            return;
        } else {
            System.out.print(root.val + " ");
            preOrder(root.left);
            preOrder(root.right);
        }
    }

    //中序遍历
    public void inOrder(TreeNode root) {
        if (root == null) {
            return;
        } else {
            preOrder(root.left);
            System.out.print(root.val + " ");
            preOrder(root.right);
        }
    }

    //后序遍历
    public void postOrder(TreeNode root) {
        if (root == null) {
            return;
        } else {
            preOrder(root.left);
            preOrder(root.right);
            System.out.print(root.val + " ");
        }
    }

    //获取二叉树的节点个数
    public int getNodeNum(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return 1 + getNodeNum(root.left) + getNodeNum(root.right);
    }

    //获取二叉树的高度
    public int getTreeHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return 1 + max(getTreeHeight(root.left), getTreeHeight(root.right));
    }

    //创建二叉搜索树BST
    public TreeNode createSearchTree(int[] treeValues){
        TreeNode rootBST = null;
        for (int value : treeValues) {
            rootBST = insertNode(rootBST,value);
        }
        return rootBST;
    }

    //判断一个二叉树是否为二叉搜索树,时间复杂度O(1)
    public boolean isBST(TreeNode root) {
        return isBSTResolve(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
    }

    public boolean isBSTResolve(TreeNode root, int min, int max) {
        if (root == null) {
            return true;
        }
        if (root.val < min || root.val > max) {
            return false;
        }
        return isBSTResolve(root.left, min, root.val) && isBSTResolve(root.right, root.val, max);
    }

    //根据值查找二叉树搜索树root的某个节点
    public TreeNode findNode(TreeNode rootBST, int val) {
        if (rootBST == null) {
            return null;
        } else if (rootBST.val < val) {
            return findNode(rootBST.right, val);
        } else if (rootBST.val > val) {
            return findNode(rootBST.left, val);
        }
        return rootBST;
    }

    //向二叉搜索树中插入值val
    public TreeNode insertNode(TreeNode rootBST, int val) {
        if (rootBST == null) {
            rootBST = new TreeNode(val);
        } else {
            if (val < rootBST.val) {
                rootBST.left = insertNode(rootBST.left, val);
            } else if (val > rootBST.val) {
                rootBST.right = insertNode(rootBST.right, val);
            }
        }
        return rootBST;
    }

    //删除二叉树中某个值为val的节点
    public TreeNode deleteNode(TreeNode rootBST, int val) {
        if (findNode(rootBST, val) == null) {
            System.out.println("要删除的节点不存在!");
        } else {
            if (val < rootBST.val) {
                rootBST.left = deleteNode(rootBST.left, val);
            } else if (val > rootBST.val) {
                rootBST.right = deleteNode(rootBST.right, val);
            } else {  //rootBST就是要被删除的节点
                if (rootBST.left != null && rootBST.right != null) {  //被删除的节点的左右子节点均存在
                    TreeNode tmp = findMinNode(rootBST.right);  //从右子树找到值最小的节点填充删除节点
                    rootBST.val = tmp.val;
                    rootBST.right = deleteNode(rootBST.right, rootBST.val);  //删除右子树值最小的元素
                } else {  //被删除的节点只有一个或者无子节点存在
                    //被删除节点的左子节点为空,则右子节点取代根节点
                    if (rootBST.left == null) {
                        rootBST = rootBST.right;
                    } else {
                        rootBST = rootBST.left;
                    }
                }
            }
        }
        return rootBST;
    }
    // 找到二叉搜索树中值最小的节点
    public TreeNode findMinNode(TreeNode rootBST) {
        if (rootBST == null) {
            return null;
        } else if (rootBST.left == null) {
            return rootBST;
        }
        return findMinNode(rootBST.left);
    }
}

3.TreeHelperTest.java

package test;

import structure.TreeHelper;
import structure.TreeNode;

class treeHelperTest {
    public static void main(String[] args) {
        String treeNodeValues = "1,2,#,#,3,4,#,#,5,6,#,8,#,#";
        TreeHelper treeHelper = new TreeHelper();
        treeHelper.setValues(treeNodeValues);
        try {
            TreeNode root = treeHelper.createTree();
            System.out.println("创建二叉树成功!");

            System.out.println("前序遍历二叉树:");
            treeHelper.preOrder(root);
            System.out.println();

            System.out.println("中序遍历二叉树:");
            treeHelper.inOrder(root);
            System.out.println();

            System.out.println("后序遍历二叉树:");
            treeHelper.postOrder(root);
            System.out.println();

            System.out.printf("二叉树的节点数目:%d\n", treeHelper.getNodeNum(root));

            System.out.printf("二叉树的高度:%d\n", treeHelper.getTreeHeight(root));

            System.out.println("二叉树是否为二叉搜索树:" + String.valueOf(treeHelper.isBST(root)));
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            TreeNode rootBST = treeHelper.createSearchTree(new int[]{2, 4, 3, 1, 9, 7, 6, 8});
            System.out.println("创建二叉搜索树成功!");

            System.out.println("二叉树是否为二叉搜索树:" + String.valueOf(treeHelper.isBST(rootBST)));

            System.out.println("中序遍历二叉搜索树:");
            treeHelper.inOrder(rootBST);
            System.out.println();

            rootBST = treeHelper.insertNode(rootBST, 5);
            System.out.println("中序遍历插入5后的二叉搜索树:");
            treeHelper.inOrder(rootBST);
            System.out.println();

            rootBST = treeHelper.deleteNode(rootBST, 6);
            System.out.println("中序遍历删除6后的二叉搜索树:");
            treeHelper.inOrder(rootBST);
            System.out.println();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

测试结果如下

4.剑指Offer在线编程第18道题"二叉树的镜像"

Solution18

import structure.TreeHelper;
import structure.TreeNode;
/*
 * Q:操作给定的二叉树,将其变换为源二叉树的镜像
 * tag: 树
 */
public class Solution18 {

  public static void main(String[] args) {
    Solution18 s = new Solution18();
    s.testMirror();
  }

  public void Mirror(TreeNode root) {
    if(root == null){
      return;
    }
    if(root.left == null){
      root.left = root.right;
      root.right = null;
      Mirror(root.left);
    }
    else if(root.right == null){
      root.right = root.left;
      root.left = null;
      Mirror(root.right);
    }
    else{
      TreeNode temp = root.left;
      root.left = root.right;
      root.right = temp;
      Mirror(root.right);
      Mirror(root.left);
    }
  }

  public void testMirror(){
    TreeHelper treeHelper = new TreeHelper();
    String treeValues = "1,2,#,#,3,4,#,#,5,6,#,8,#,#";
    treeHelper.setValues(treeValues);
    TreeNode root = treeHelper.createTree();

    System.out.println("中序遍历二叉树:");
    treeHelper.inOrder(root);
    System.out.println();

    Mirror(root);

    System.out.println("中序遍历二叉树的镜像:");
    treeHelper.inOrder(root);
    System.out.println();

  }
}

运行结果如下:

原文地址:https://www.cnblogs.com/geekHao/p/12146557.html

时间: 2024-07-31 16:40:25

Leetcode 与树(TreeNode )相关的题解测试工具函数总结的相关文章

【LeetCode】树(共94题)

[94]Binary Tree Inorder Traversal [95]Unique Binary Search Trees II (2018年11月14日,算法群) 给了一个 n,返回结点是 1 - n 的所有形态的BST. 题解:枚举每个根节点 r, 然后递归的生成左右子树的所有集合,然后做笛卡尔积. 1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *

Leetcode解题-树(5.0.0)基础类

与第二章类似,LeetCode指定了TreeNode实现.为了方便后续习题的编写和测试,创建一个基础父类,包含TreeNode实现,以及create()和print()创建和打印树的方法.其中create()采用类似"堆"的方式,用数组表示树形结构,复习一下,左右子结点就是2*i和2*i+1.而print()方法采用前序遍历的方式,通过额外一个参数level确定当前结点的深度,从而打印一些制表符或其他符号来表示出结点的父子关系.两个核心方法都使用递归的方式,实现起来非常简洁! 注:实现

LeetCode: 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. 题解: 题意比较清楚, 找到从root出发最长的一条路径的长度. 采用DFS即可. 相似的一道题: Minimux Depth of Binary Tree 解法: http://

uva 12299 线段树 点相关的操作模板

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=502&page=show_problem&problem=3720 唯一值得一说的就是shift,变成更新点就行 这道题主要是测试下我做的算法模板 先贴模板 /**************************************************************** 2014.4 By Pilgr

LeetCode: Longest Substring Without Repeating Characters 题解

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest subst

LeetCode: Palindrome 回文相关题目

LeetCode: Palindrome 回文相关题目汇总 LeetCode: Palindrome Partitioning 解题报告 LeetCode: Palindrome Partitioning II 解题报告 Leetcode:[DP]Longest Palindromic Substring 解题报告 LeetCode: Valid Palindrome 解题报告

LeetCode总结 -- 树的求和篇

树的求和属于树的题目中比较常见的,因为可以有几种变体,灵活度比较高,也可以考察到对于树的数据结构和递归的理解.一般来说这些题目就不用考虑非递归的解法了(虽然其实道理是跟LeetCode总结 -- 树的遍历篇一样的,只要掌握了应该没问题哈). LeetCode中关于树的求和有以下题目:Path SumPath Sum IISum Root to Leaf NumbersBinary Tree Maximum Path Sum 我们先来看看最常见的题目Path Sum.这道题是判断是否存在从根到叶子

数据库相关文章转载(2) MySQL自带的性能压力测试工具mysqlslap详解

PS:今天一同事问我有木有比较靠谱的mysql压力测试工具可用.其实mysql自带就有一个叫mysqlslap的压力测试工具,还是模拟的不错的.下面举例说说.mysqlslap是从5.1.4版开始的一个MySQL官方提供的压力测试工具.通过模拟多个并发客户端访问MySQL来执行压力测试,同时详细的提供了“高负荷攻击MySQL”的数据性能报告.并且能很好的对比多个存储引擎在相同环境下的并发压力性能差别.通过mysqlslap –help可以获得可用的选项,这里列一些主要的参数,更详细的说明参考官方

Android 开源项目android-open-project开发工具及测试工具解析 开发效率工具,开发自测相关,测试工具,开发及编译环境,其他

主要介绍和Android开发工具和测试工具相关的开源项目. 一.开发效率工具 Parceler 通过注解及工具类自动完成实体类 Parcelable及值传递 项目地址:https://github.com/johncarl81/parceler Json2Java 根据JSon数据自动生成对应的Java实体类,还支持Parcel.Gson Annotations对应代码自动生成.期待后续的提取父类以及多url构建整个工程的功能 项目地址:https://github.com/jonfhancoc