输入前序遍历,还原二叉树并返回中序遍历

第一步:对二叉树的结点进行定义,在TreeNode中保存
第二步:根据前序遍历还原二叉树createTable
       定义一个index表示在前序遍历中遍历过的元素的位置
       谦虚遍历数组String str
       1.空树,
       2.如果index小于数组str长度并且值不是#,则执行下面遍历
       if(index < str.length() && str.charAt(index) != '#'){
       index++;
       创建左子树
       root.left = createTable(str);
       创建右子树
       root.right = createTable(str);
       }
       未执行遍历说明str。charAt(i)为空,继续看下一个元素的值
       index++;
第三步:打印中序遍历,递归,左中右InOrder
       InOrder(root.left);
       System.out.print(root.val + " ");
       InOrder(root.right);

代码如下


public class TreeNode {
    char val;//输入的是字符串
    TreeNode left;
    TreeNode right;

    public TreeNode(char val) {
        this.val = val;
    }
}
public class Solution {
    //定义全局变量
    int index = 0;
    TreeNode root;

    //第二步:通过前序遍历还原二叉树
    public TreeNode createTable(String str) {
        if (index < str.length() && str.charAt(index) != '#') {
            root = new TreeNode(str.charAt(index));
            index++;
            //创建左子树
            root.left = createTable(str);
            //创建右子树
            root.right = createTable(str);
        } else {
            index++;
        }
        return root;
    }

    //第三步:打印中序遍历
    public void InOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        InOrder(root.left);
        System.out.print(root.val + " ");
        InOrder(root.right);
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String str = scanner.nextLine();
            Solution tree = new Solution();
            TreeNode root = tree.createTable(str);
            tree.InOrder(root);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/crazy_tan/article/details/131214199