根据字符串构建二叉树以及n叉树的层序遍历

Posted 王六六同学

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了根据字符串构建二叉树以及n叉树的层序遍历相关的知识,希望对你有一定的参考价值。

空节点用null表示
例如:[1,2,3,4,null,null,null,null,20,21]

import java.util.*;

/**
 * @author WanZi
 * @create 2022-10-22 19:58
 */
public class Main01 

    static class TreeNode 
		int val;
		TreeNode left;
		TreeNode right;
		public TreeNode(int val) 
			this.val = val;
		
   
	public static void main(String[] args) 
		TreeNode root = stringToTree("[1,2,3,4,,null,null,null,null,20,21]");
	


    public static TreeNode stringToTree(String str)
        String[] elems = stringToArray(str);
        if (null == elems) 
            return null;
        

        TreeNode root = createTree(elems, 0);
        return root;
    
    //递归构建二叉树
    private static TreeNode createTree(String[] arr, int index) 
        TreeNode tn = null;
        if (index < arr.length) 
            if (arr[index].equals("null")) 
                return null;
            
            Integer val = Integer.valueOf(arr[index]);
            tn = new TreeNode(val);
            // 构建二叉树左子树
            tn.left = createTree(arr, 2 * index + 1);
            // 构建二叉树右子树
            tn.right = createTree(arr, 2 * index + 2);
        
        return tn;
    
    public static String[] stringToArray(String str)
        if(null != str && str.equals(""))
            return null;
        
        String[] fileds = str.split(",");
        return fileds;
    




遍历n叉树


	static class TreeNode
        public  int val;
        public List<TreeNode> child;
        public TreeNode() 
        

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

        public TreeNode(int val, List<TreeNode> child) 
            this.val = val;
            this.child = child;
        
    
    //遍历n叉树
    public static List<List<Integer>> levelOrder(TreeNode root)
        List<List<Integer>> res = new ArrayList<>();
        if(root == null)
            return res;
        
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        while(!q.isEmpty())
            int n = q.size();
            List<Integer> level = new ArrayList<>();
            while(n-- > 0)
                TreeNode node = q.poll();
                level.add(node.val);
                for(TreeNode child : node.child)
                    if(child != null)
                        q.offer(child);
                    
                
            
            res.add(level);
        
        return res;
    

以上是关于根据字符串构建二叉树以及n叉树的层序遍历的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 102. 二叉树的层序遍历 Java

(二叉树)原来二叉树的层序遍历这么简单!!!

2021-4-9天梯赛补题(完全二叉树的层序遍历)

429. N 叉树的层序遍历

面试---算法面试

二叉树算法—广度搜索算法使用以及变形