中级农民
- 积分
- 155
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2014-4-17
- 最后登录
- 1970-1-1
|
写了下第一题的代码
- public class BinayTreeExpressString {
-
- static class Node {
- int val;
- Node left;
- Node right;
- public Node(int val) {
- this.val = val;
- }
- }
- public static Node useBinayTreeExpressString(String str) {
- if (str == null || str.length() == 0) {
- return null;
- }
- if (str.length() == 1) {
- return new Node(Integer.valueOf(str.charAt(0)));
- }
- int len = str.length();
- int level = (int)(Math.log(len) / Math.log(2));
- Node root = new Node(-1);
- int index = 0;
- Queue<Node> queue = new LinkedList<Node>();
- queue.offer(root);
- System.out.println(level);
- while (index < level) {
- index++;
- if (index < level) {
- int size = queue.size();
- for (int i = 0; i < size; i++) {
- Node cur = queue.poll();
- cur.left = new Node(-1);
- queue.offer(cur.left);
- cur.right = new Node(-1);
- queue.offer(cur.right);
- }
- } else {
- for (int i = 0; i < str.length();) {
- Node cur = queue.poll();
- cur.left = new Node((str.charAt(i++) - '0'));
- if (i < str.length()) {
- cur.right = new Node((str.charAt(i++) - '0'));
- }
- }
- }
- }
- return root;
- }
- public static Node useBinayTreeExpressStringFollowUp(String str) {
- if (str == null || str.length() == 0) {
- return null;
- }
- if (str.length() == 1) {
- return new Node((str.charAt(0) - '0'));
- }
- return helper(str, 0, str.length() - 1);
- }
- private static Node helper(String str, int start, int end) {
- if (start > end) {
- return null;
- }
- if (start == end || isAllTheSame(str, start, end)) {
- return new Node((str.charAt(start) - '0'));
- }
- int mid = (end - start) / 2 + start;
- Node node = new Node(-1);
- node.left = helper(str, start, mid);
- node.right = helper(str, mid + 1, end);
- return node;
- }
- private static boolean isAllTheSame(String str, int start, int end) {
- char c = str.charAt(start++);
- while (start <= end) {
- if (str.charAt(start) != c) {
- return false;
- }
- start++;
- }
- return true;
- }
-
- public static void print(Node node) {
- if (node == null) {
- return;
- }
- print(node.left);
- if (node.left == null && node.right == null) {
- System.out.print(node.val);
- }
- print(node.right);
- }
- public static void printTree(Node node) {
- if (node == null) {
- return;
- }
- printTree(node.left);
- System.out.print(node.val);
- printTree(node.right);
- }
- public static void main(String[] args) {
- // Node node = useBinayTreeExpressString("1011");
- Node node = useBinayTreeExpressStringFollowUp("1011");
- printTree(node);
- }
- }
复制代码 |
|