在作LeetCode的題時,只須要編輯算法核心邏輯便可,如邏輯正確則執行成功,但若是邏輯出錯,想要調試看看問題出在哪裏LeetCode平臺就無能爲力了。本博客講述如何在IDE上調試代碼。java
下面就樹的相關算法,提供簡單的IDE調試方法。node
LeetCode中的樹節點是:算法
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */
1. 則建立對應的java類爲:eclipse
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],構建樹spa
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);執行後產生對應的樹調試
如此,在類TreeTest 中編輯對應核心邏輯,在TreeTest 的main方法中建立對應的測試樣例,就能夠使用eclipse進行調試了。code
爲了獲得而努力blog
2019-04-05ip
轉載給註明來處