# 如何在IDE（eclipse）中debug LeetCode的树算法

LeetCode中的树节点是：

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/

1. 则创建对应的java类为：

package com.livy.tree.utils;

public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x){
val = x;
}
}

2.按层构建树，下面的i<= (n-3)/2是对2*i+2<=n-1的变形

 1 package com.livy.tree.utils;
2
3 public class Tree {
4     public void createTreeAsLevel(TreeNode[] nodes){
5         int n = nodes.length;
6         int flag = 0;//按层构造时一个值为null，则它之后的孩子序号应该相应减2flag
7         for(int i=0; 2*i+1 < n-1; i++){
8             if(nodes[i] != null){
9                 nodes[i].left = nodes[2*i+1-2*flag];
10                 nodes[i].right = 2*i+2 == n ? null : nodes[2*i+2-2*flag];
11             }else{
12                 flag++;
13             }
14         }
15         System.out.println();
16     }
17 }

3. 对测试样例[5,3,6,2,4,null,7]，构建树

package com.livy.tree.utils;

import java.util.Vector;

public class TreeTest {
public boolean findTarget(TreeNode root, int k) {
//LeetCode的核心代码
}

public static void main(String[] args) {
Integer[] data = {5,3,6,2,4,null,7};
TreeNode[] nodes = new TreeNode[data.length];
for(int i=0; i<data.length; i++){
nodes[i] = data[i]==null ? null : new TreeNode(data[i].intValue());
}
Tree tree = new Tree();
tree.createTreeAsLevel(nodes);
TreeTest tt = new TreeTest();
System.out.println(tt.findTarget(nodes[0], -1));
}
}

tree.createTreeAsLevel(nodes);执行后产生对应的树

2019-04-05

posted @ 2019-04-05 11:54  为了得到而努力  阅读(1530)  评论(0编辑  收藏  举报