二叉树相关操作 发表于 2020-07-29 | 分类于 算法面试题 | 字数统计: 153 | 阅读时长 ≈ 1 12345678910111213141516171819202122232425262728293031323334353637383940public static TreeNode stringToTreeNode(String input) { input = input.trim(); if (input.length() == 0) { return null; } String[] parts = input.split(","); String item = parts[0]; TreeNode root = new TreeNode(Integer.parseInt(item)); Queue<TreeNode> nodeQueue = new LinkedList<>(); nodeQueue.add(root); int index = 1; while(!nodeQueue.isEmpty()) { TreeNode node = nodeQueue.remove(); if (index == parts.length) { break; } item = parts[index++]; item = item.trim(); if (!item.equals("null")) { int leftNumber = Integer.parseInt(item); node.left = new TreeNode(leftNumber); nodeQueue.add(node.left); } if (index == parts.length) { break; } item = parts[index++]; item = item.trim(); if (!item.equals("null")) { int rightNumber = Integer.parseInt(item); node.right = new TreeNode(rightNumber); nodeQueue.add(node.right); } } return root;}