LeetCode 跟树结构相关的题目的测试用例中大多是通过String数组来构造树。例如{2,#,3,#,4,#,5,#,6},可以构造出如下的树(将树结构逆时针选择90度显示):

6
            5
        4
    3
2

很直观地可以理解,输入的String数组是对树结构进行“层序”遍历得到的结果。以下代码用于构造树结构,并提供printTree用于打印树结构。

package util;

import java.util.LinkedList;
import java.util.Queue; public class util {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right; TreeNode(int x) {
val = x;
}
} /*
* construct TreeNode from a array format string, for test cases of LeetCode
*/
public static TreeNode createTree(String tree) {
// {1,2,3,4,#,#,#,5,#,6,#,7,#,8}
String[] ss = tree.split(",");
return createTree(ss);
} public static TreeNode createTree(String[] tree) {
Queue<TreeNode> q = new LinkedList<TreeNode>();
// 1st one should not be #
TreeNode root = constructOne(tree[0]);
q.add(root);
int idx = 1;
while (!q.isEmpty()) { TreeNode tn = q.poll();
if (tn == null) {
continue;
}
// construct tn's left&right node
// when to stop
if (idx == tree.length) {
break;
}
TreeNode left_ = constructOne(tree[idx]);
tn.left = left_;
q.add(left_);
idx++;
if (idx == tree.length) {
break;
}
TreeNode right_ = constructOne(tree[idx]);
idx++; tn.right = right_;
// add to queue
q.add(right_);
} return root; } private static void printNode(TreeNode tn, int indent) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < indent; i++) {
sb.append("\t");
}
sb.append(tn.val);
System.out.println(sb.toString());
} public static void printTree(TreeNode root, int indent) {
if (root == null) {
return;
}
// if (root.left == null && root.right == null) {
// printNode(root, indent);
// }
// right
printTree(root.right, indent + 1);
// self
printNode(root, indent);
// left
printTree(root.left, indent + 1);
} public static void printTree(TreeNode root) {
// right first
printTree(root, 0);
} private static TreeNode constructOne(String s) {
if (s.compareTo("#") == 0) {
return null;
} else {
return new TreeNode(Integer.parseInt(s));
}
} public static void main(String args[]) {
TreeNode tn = createTree("2,#,3,#,4,#,5,#,6");
printTree(tn);
}
}

[leetcode] 根据String数组构造TreeNode,用于LeetCode树结构相关的测试用例的更多相关文章

  1. (string 数组) leetcode 804. Unique Morse Code Words

    International Morse Code defines a standard encoding where each letter is mapped to a series of dots ...

  2. [LeetCode] Interleaving String 交织相错的字符串

    Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. For example, Given: s1 ...

  3. 【LeetCode题解】数组Array

    1. 数组 直观地看,数组(Array)为一个二元组<index, value>的集合--对于每一个index,都有一个value与之对应.C语言中,以"连续的存储单元" ...

  4. [LeetCode] Repeated String Match 重复字符串匹配

    Given two strings A and B, find the minimum number of times A has to be repeated such that B is a su ...

  5. [LeetCode] Construct String from Binary Tree 根据二叉树创建字符串

    You need to construct a string consists of parenthesis and integers from a binary tree with the preo ...

  6. C#LeetCode刷题-数组

    数组篇 # 题名 刷题 通过率 难度 1 两数之和 C#LeetCode刷题之#1-两数之和(Two Sum) 43.1% 简单 4 两个排序数组的中位数 C#LeetCode刷题之#4-两个排序数组 ...

  7. [LeetCode] Reverse String 翻转字符串

    Write a function that takes a string as input and returns the string reversed. Example: Given s = &q ...

  8. [LeetCode] Magical String 神奇字符串

    A magical string S consists of only '1' and '2' and obeys the following rules: The string S is magic ...

  9. [LeetCode] Reverse String II 翻转字符串之二

    Given a string and an integer k, you need to reverse the first k characters for every 2k characters ...

随机推荐

  1. java之ubuntu12.04 开发环境配制

    配置java开发环境,即安装jdk: 1.配置环境变量 ,更改/etc/profile文件:sudo gedit /etc/profile; 在文件最后加上如下几行(其实跟windows下的配置原理一 ...

  2. <script type="text/javascript" src="<%=path %>/pages/js/arsis/area.js?v=1.01"></script> 为什么在最后加? v+1.01

    不写也可以 是为了js改变以后 ,名字未变 ,如果原来有的浏览器加载 了,遇到相同名字的就是引用缓存,不在从新加载.会出现错误.加上后 会重新加载. css 引用后面也一样.

  3. Go语言的传值与传引用

    Go语言里的传值与传引用大致与C语言中一致,但有2个特例,map和channel默认传引用,也就是说可以直接修改传入的参数,其他的情况如果不用指针的话,传入的都是参数的副本,在函数中修改不会改变调用者 ...

  4. Python的平凡之路(14)

    一.什么是HTML HTML(Hyper Text Mark-up Language ) 即超文本标记语言,是 WWW 的描述语言,由 Tim Berners-lee提出.设计 HTML 语言的目的是 ...

  5. 转载——C++控制台贪吃蛇代码

    游戏截图: 以下是3个代码文件: Snake_Class.h文件: 1 #ifndef SNAKE 2 #define SNAKE 3 4 #include<windows.h> 5 #i ...

  6. hadoop2的高可用性

    1   hadoop2  namenode由一个节点变成两个节点,同时在线,且同时只有一个是活跃的,如果一个出了问题,另外一个立即接替:没必要配置Secondary NameNode.Checkpoi ...

  7. javac找不到或无法加载主类 com.sun.tools.javac.Main

    在安装jdk后或者以前安装了jdk某时使用javac编译java文件时出现找不到或无法加载主类com.sun.tools.javac.Main,这个问题时,网上一般都说是环境变量配置不对,这样的说法其 ...

  8. [解决方案] pythonchallenge level 0

    http://www.pythonchallenge.com/pc/def/0.html 问题: 2^38 >>> 2**38 >>>274877906944L 输 ...

  9. arch安装

    [archwiki-install]: (https://wiki.archlinux.org/index.php/Installation_guide) uefi+gpt Gummiboot #se ...

  10. 数据结构《17》---- 自动补齐之《二》----Ternary Search Tree

    一. 序言 上一篇文章中,给出了 trie 树的一个实现.可以看到,trie 树有一个巨大的弊病,内存占用过大. 本文给出另一种数据结构来解决上述问题---- Ternary Search Tree ...