LeetCode中将测试案例中的数组转化成对应的二叉树

待转化数组:

[3,1,null,null,2]

用途:没啥用,在leetcode上写树的题的时候,不需要再挨个节点的构造树。

思路:

1、将方括号去除

2、以逗号为分割点进行,将待转化数组分割成字符数组记为strList

3、(层次遍历思想)在对strList进行遍历时,数组的第一个值必然为根节点,将该节点放到队列中。

4、在队列中取出一个节点记为n1,这时候当前节点i的后面两个索引 i+1,i+2则代表n1的左右节点,若i+1,i+2小于strList的长度,且对应的值不为null,则可以将n1的左右节点先后放入队列中,直至循环结束。

代码:

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author zhc
 * @date 2020/2/27 11:29
 */
public class ListToTree {
    public static class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x){
            val = x;
        }
    }

    public TreeNode listToTree(String src){
        src = src.substring(1,src.length()-1);
        String[] strList = src.split(",");

        TreeNode root  ;
        TreeNode result = null;
        Queue queue = new LinkedList<>();
        for (int i =0 ; i< strList.length ; i++){
            if (i == 0){
                root = new TreeNode(Integer.parseInt(strList[i]));
                result = root;
                queue.add(root);
            }
            if (!queue.isEmpty()){
                root = queue.poll();
            }else {
                break;
            }
            if ( i+1 < strList.length  && !strList[i+1].equals( "null")){
                root.left = new TreeNode(Integer.parseInt(strList[i +1]));
                queue.add(root.left);
            }
            if ( i + 2 < strList.length && !strList[i+2].equals( "null")){
                root.right = new TreeNode(Integer.parseInt(strList[i +2]));
                queue.add(root.right);
            }
            i = i +1;
        }
       return result;
    }
    public static void main(String[] args) {
        System.out.println(new ListToTree().listToTree("[3,1,null,null,2]"));
    }
}

调试结果:

LeetCode中将测试案例中的数组转化成对应的二叉树_第1张图片

你可能感兴趣的:(算法学习)