📣 独立日限时特惠: VIP通行证立减$68
查看: 6702| 回复: 26
跳转到指定楼层
上一主题 下一主题
收起左侧

[Leetcode] Leetcode个人刷题思路和自我督促贴

🔗
jaly50 | 只看该作者 |倒序浏览
全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
本帖最后由 jaly50 于 2014-12-29 12:30 编辑

开个贴子自我督促一下哈~
顺便分享一下自己的思路,欢迎讨论~

2楼:Anagrams
3楼:Wildcard Matching
4-5楼:Jump Game II
6楼:Flatten Binary Tree to Linked List

7楼:Insert Interval
8楼:Construct Binary Tree from Preorder and Inorder Traversal

9楼:Construct Binary Tree from Postorder and Inorder Traversal

10楼:Validate Binary Search Tree

11楼: Simplify Path

12楼:Set Matrix Zeroes
13楼:Permutation Sequence
14楼: Restore IP Addresses

15楼: Subsets II

16楼:Partition List


18楼:Recover Binary Search Tree

19楼: Interleaving String

20楼   Minimum Window Substring

21楼 Largest Rectangle in Histogram

22楼 Maximal Rectangle

23楼 Excel Sheet Column Title

24楼 Maximum Gap

25楼 Fraction to Recurring Decimal






















评分

参与人数 6大米 +54 收起 理由
williamwjs + 5 感谢分享!
mnmunknown + 3 坚持的不错,再接再厉!
微斯渝 + 10 加油~
yyt913 + 11 ebiz师姐holy high~
jby1797 + 5 jaly加油!

查看全部评分


上一篇:用c刷cc150好痛苦
下一篇:CC上一道关于抽象类的设计问题
推荐
 楼主| jaly50 2014-12-22 10:01:48 | 只看该作者
全局:
  1. import java.util.Arrays;
  2. /*
  3. * Date:12/21/2014 Sun 5:59 PM
  4. * @author: Scarlett Chen
  5. */

  6. public class SurroundedRegion {
  7.             boolean [] hasEdge;
  8.             int[] union;
  9.             /*
  10.              * 一开始用了recursive dfs, 还发生了stackoverflow.QAQ .
  11.              * 最后用了algorithm1的unionfind写的~!感觉自己代码实现能力有提高呢!.
  12.              */
  13.             public void solve(char[][] board) {
  14.              int n = board.length;
  15.              if (n<1) return;
  16.              int m = board[0].length;
  17.              hasEdge = new boolean[n*m];
  18.              union = new int[n*m];
  19.              int pos;
  20.              for (int i=0; i<n; i++) {
  21.                      for (int j=0; j<m; j++) {
  22.                             pos = i*m +j;
  23.                             hasEdge[pos] = (i==0 ||j==0||i==n-1||j==m-1) ? true : false;
  24.                             union[pos] = pos;
  25.                             if (i>0 && board[i][j]== board[i-1][j]) {
  26.                                     union(pos, pos-m);
  27.                             }
  28.                             if (j>0 && board[i][j] == board[i][j-1]) {
  29.                                     union(pos, pos-1);
  30.                             }
  31.                       
  32.                      }
  33.              }
  34.              for (int i=0; i<n; i++) {
  35.                      for (int j=0; j<m; j++) {
  36.                              pos = i*m+j;
  37.                              if (board[i][j]=='O' &&  !hasEdge[findRoot(pos)]) {
  38.                                      board[i][j] = 'X';
  39.                              }
  40.                      }
  41.              }
  42.              for (int i=0; i<board.length; i++)
  43.                                 System.out.println(Arrays.toString(board[i]));
  44.              
  45.             }
  46.             
  47.             private void union(int x, int y) {
  48.                         int rootX = findRoot(x);
  49.                         int rootY = findRoot(y);
  50.                         union[rootX] = rootY;
  51.                         boolean hasedge = hasEdge[rootX] || hasEdge[rootY];
  52.                         hasEdge[rootY] = hasedge;
  53.        
  54.                 }

  55.                 private int findRoot(int x) {
  56.                         if (union[x]==x) return x;
  57.                         else return findRoot(union[x]);
  58.                 }


  59.         public static void main(String[] args) {
  60.                 // TODO Auto-generated method stub
  61.                 SurroundedRegion sr = new SurroundedRegion();
  62.                 char[][] board = new char[][] {{'X', 'X', 'X', 'X'},
  63.                                                                                 {'X', 'O', 'O', 'X'},
  64.                                                                                 {'X', 'X', 'O', 'X'},
  65.                                                                                 {'X', 'O' ,'X' ,'X'}};
  66.                 sr.solve(board);
  67.         }
  68.        
  69.        
  70.         //Failed
  71.         //Limitation in recursion depth
  72.         //sometimes we need to use stack to do bfs or dfs.
  73.          boolean[][] withEdge;
  74.             char[][] board;
  75.             int n;
  76.             int m;
  77.         public void solve_fail(char[][] board) {
  78.                n= board.length;
  79.                this. board = board;
  80.                if (n<1) return;
  81.                m = board[0].length;
  82.                withEdge = new boolean[n][m];
  83.                for (int i=0; i<n; i++) {
  84.                    Arrays.fill(withEdge[i], false);
  85.                }
  86.                 for (int i=0; i<n; i++) {
  87.                  if (board[i][0]=='O') {
  88.                      if (!withEdge[i][0]) {
  89.                          dfs(i,0);
  90.                      }
  91.                  }
  92.                 if (board[i][m-1]=='O') {
  93.                      if (!withEdge[i][m-1]) {
  94.                          dfs(i,m-1);
  95.                      }
  96.                  }
  97.                 }
  98.                for (int j=0; j<m; j++) {
  99.                    if (board[0][j]=='O') {
  100.                        if (!withEdge[0][j]) {
  101.                          dfs(0,j);
  102.                        }
  103.                    }
  104.                   if (board[n-1][j]=='O') {
  105.                        if (!withEdge[n-1][j]) {
  106.                          dfs(n-1,j);
  107.                        }
  108.                    }
  109.                }
  110.               for (int i=0; i<n; i++) {
  111.                   for (int j=0; j<board[0].length; j++) {
  112.                       if (board[i][j]=='O' && !withEdge[i][j]) {
  113.                           board[i][j] = 'X';
  114.                       }
  115.                   }
  116.               }
  117.                 
  118.             }
  119.             public void dfs(int row, int col) {
  120.                     withEdge[row][col] = true;
  121.                 if (row>0 && board[row-1][col]=='O' && !withEdge[row-1][col]) {
  122.                     dfs(row-1, col);
  123.                 }
  124.                 if (row<n-1 && board[row+1][col]=='O' && !withEdge[row+1][col]) {
  125.                     dfs(row+1, col);
  126.                 }
  127.                 if (col>0 && board[row][col-1]=='O' && !withEdge[row][col-1]) {
  128.                     dfs(row, col-1);
  129.                 }
  130.                 if (col<board[0].length-1 && board[row][col+1]=='O' && !withEdge[row][col+1]) {
  131.                     dfs(row, col+1);
  132.                 }
  133.             }
  134.        
  135. }
复制代码
回复

使用道具 举报

推荐
 楼主| jaly50 2014-12-28 13:06:07 | 只看该作者
全局:
  1. import java.util.HashMap;
  2. import java.util.Map;

  3. /*
  4. * LeetCode 155 Minimum Window Substring
  5. * Given a string S and a string T,
  6. * find the minimum window in S which will contain all the characters in T in complexity O(n).
  7. * @author: Scarlett Chen
  8. * @date: 12/27/2014 Sat 8:36 PM
  9. * Time: o(2n)
  10. * space: o(n)
  11. * 思路:记录minWindow的开始点sb,每次匹配完T的值后,删掉第一个点,继续往后找,直到T再次匹配完全。
  12. * 每次完全匹配时,更新minWindown是否有更小。
  13. */
  14. public class MinWindow {
  15.         public static String minWindow(String S, String T) {
  16.                Map<Character,Integer> map = new HashMap<Character, Integer>();
  17.                String minWindow = S;
  18.                if (T.length()> S.length()) return "";
  19.                if (T.equals(S)) return minWindow;
  20.                int count  = T.length();
  21.                for (int i=0; i<count; i++) {
  22.                    char ch = T.charAt(i);
  23.                    if (map.containsKey(ch)) {
  24.                        map.put(ch, map.get(ch)-1);
  25.                    }
  26.                    else map.put(ch, -1);
  27.                }
  28.                int sb = -1;
  29.                boolean ansExist = false;
  30.                for (int i=0; i<S.length(); i++ ) {
  31.                    char ch = S.charAt(i);
  32.                    if (map.containsKey(ch)) {
  33.                            System.out.println(ch);
  34.                            //First beginning of the window
  35.                        if (sb==-1) sb = i;
  36.                        map.put(ch, map.get(ch)+1);
  37.                        if (map.get(ch)<=0)
  38.                                count--;
  39.                        while (count==0) {
  40.                                ansExist = true;
  41.                            minWindow =i-sb+1 <minWindow.length() ? S.substring(sb,i+1): minWindow;
  42.                            ch = S.charAt(sb);
  43.                           // if (map.containsKey(ch))  must contain, since sb is the begining of the minwindow
  44.                                    map.put(ch, map.get(ch)-1);
  45.                            if (map.get(ch)<0) count++;
  46.                         sb++;
  47.                         while (sb <= S.length()-T.length() && !map.containsKey(S.charAt(sb)))
  48.                                   sb++;
  49.                         if (sb>S.length()-T.length()) return minWindow;
  50.                            }
  51.                          
  52.                            
  53.                        }
  54.                    }
  55.                   
  56.                    
  57.                
  58.               return ansExist? minWindow: "";   
  59.             }
  60.         public static void main(String[] args) {
  61.                 System.out.println(minWindow("bdab","ab"));
  62.    
  63.         }

  64. }
复制代码
回复

使用道具 举报

推荐
 楼主| jaly50 2014-11-23 03:18:52 | 只看该作者
全局:
  1. /*
  2. * Author: Scarlett
  3. * Date: 11/21/2014 Fri 11:12 PM
  4. * LeetCode: 110  Anagrams
  5. * thought: HashMap
  6. * If only using HashMap, it will TLE. Since map[i].equals(map[j]) cost m time. (m is the length of a string)
  7. * Way to improve: To calculate total ASCii in one String, check whether TotalASCII[i]==totalASCII[b], it only cost 1 time.
  8. */



  9. import java.util.ArrayList;
  10. import java.util.Arrays;
  11. import java.util.Comparator;
  12. import java.util.HashMap;
  13. import java.util.List;
  14. import java.util.Map;

  15. // Same length? Duplicated group with different length? First step is to clarify the scope.
  16. //TLE QAQ 是不是str如果按长度排序,就可以再少点time consuming
  17. public class Anagrams {
  18.         public List<String> anagrams_buxiele(String[] strs) {
  19.                  List<String> list = new ArrayList<String>();
  20.                  return list;

  21.         }
  22.         public List<String> anagrams(String[] strs) {
  23.         List<String> list = new ArrayList<String>();
  24.                 Arrays.sort(strs,new Comparator<String>(){

  25.                         @Override
  26.                         public int compare(String o1, String o2) {
  27.                                 if (o1.length()<o2.length())  return -1;
  28.                                 else if (o1.length()>o2.length()) return 1;
  29.                                 return 0;
  30.                         }});
  31.                
  32.         int len = strs.length;
  33.         
  34.         //To reduce time, judging whether they are same total accil QAQ
  35.         //it works!!! GREAT!!!!!
  36.         int[] totalAC = new int[len];
  37.         Arrays.fill(totalAC, 0);
  38.         
  39.         //Make every String a map
  40.         Map<Character,Integer>[] map =new HashMap[len];
  41.         for (int i=0; i<len; i++) {
  42.            map[i] = new HashMap<Character,Integer>();
  43.            char[] s =strs[i].toCharArray();
  44.            for (char ch:s) {
  45.                    totalAC[i] += ch-'0';
  46.                    if (map[i].containsKey(ch) ) {
  47.                    map[i].put(ch,map[i].get(ch)+1);
  48.                }
  49.                else map[i].put(ch,1);
  50.            }
  51.         }
  52.         //Try some methods to reduce consuming time QAQ
  53.         //Mark strings which are already in the groups
  54.         boolean[] mark = new boolean[len];
  55.         Arrays.fill(mark, false);
  56.         
  57.         
  58.         
  59.         // To detect whether they are anagrams by compare map
  60.         for (int i=0; i<len; i++) {
  61.                 if (!mark[i])
  62.             for (int j=i+1; j<len; j++) {
  63.                 if (strs[i].length()!=strs[j].length()) break;
  64.                 if (totalAC[i] !=totalAC[j]) continue;
  65.                 if (map[i].equals(map[j])) {
  66.                          if (!mark[i])  list.add(strs[i]);
  67.                     list.add(strs[j]);
  68.                     mark[i] = true;
  69.                     mark[j] = true;
  70.                 }
  71.             }
  72.         }
  73.         return list;
  74.     }
  75.    

  76.         public static void main(String[] args) {
  77.                 // TODO Auto-generated method stub
  78.                 Anagrams a = new Anagrams();
  79.                 String[] strs = new String[]{"dog","cat","god","tac"};
  80.                 System.out.println(a.anagrams(strs));
  81.         }

  82. }
复制代码
回复

使用道具 举报

🔗
 楼主| jaly50 2014-11-23 03:19:41 | 只看该作者
全局:
本帖最后由 jaly50 于 2014-12-14 11:19 编辑
  1. /*
  2. * LeetCode 141 Wild Card
  3. * Author: Scarlett Chen
  4. * Time: 12/13/2014 Sat 10:17 PM
  5. * 二十天以前不会写,参考了别人的答案。
  6. * 今天用那个dp的思路。发现还有很多细节需要注意
  7. */
  8. import java.util.HashMap;
  9. import java.util.Map;
  10. //https://oj.leetcode.com/discuss/10133/linear-runtime-and-constant-space-solution
  11. public class Wildcard {
  12.          public boolean isMatch(String s, String p) {
  13.                int len1 = s.length();
  14.                int len2 = p.length();
  15.                int j=0;
  16.                int i=0;
  17.                int prej=-1, prei=0;
  18.                // p串是零的情况
  19.                if (len1!=0 && len2==0) return false;
  20.                while (i<len1) {
  21.                    char cs = s.charAt(i);
  22.                    char cp;
  23.                    //直接不匹配 没有*号的情况
  24.                    if (j==-1) return false;
  25.                    if (j<len2) cp = p.charAt(j);
  26.                    else  cp = ' ';
  27.                    if (cs==cp || cp=='?') {
  28.                        i++;
  29.                        j++;
  30.                    }
  31.                    else if (cp=='*') {
  32.                        prej = j;
  33.                        prei = i;
  34.                        j++;
  35.                       
  36.                    }
  37.                    else {
  38.                      j = prej;
  39.                      i = ++prei;
  40.                    }
  41.                }
  42.                //注意这里不只一个值要注意,要看看是不是后面都是*号,才能放过它。
  43.                while (j<len2) {
  44.                       if (p.charAt(j)=='*') j++; else return false;
  45.                       
  46.                }
  47.              
  48.               return true;  
  49.             }
复制代码
回复

使用道具 举报

🔗
 楼主| jaly50 2014-11-26 11:35:00 | 只看该作者
全局:
/*
* LeetCode Jump Game II
*
* 需要思考,但是实现很容易。一次过~
* Date:11/25/2014 Tue 10:25 PM
* 思路:dp
*    在i的位置上,每次可以跳子距离(0,A[i]) , 就可以算f[i到i+A[i]]的次数了
*    f[i+j] = min (f[i+j], f[i]+1)  (j is in [1,A[i]])
*    再加点优化, if i<j, A[i]>A[j]+distance(i,j), 那么f[j]就不用算
*
*/
回复

使用道具 举报

🔗
 楼主| jaly50 2014-11-26 11:35:21 | 只看该作者
全局:
  1. public int jump(int[] A) {
  2.         int[] f = new int[A.length];
  3.         Arrays.fill(f,Integer.MAX_VALUE);
  4.         f[0]=0;
  5.         int max=0;
  6.       for (int i=0; i<A.length; i++) {
  7.           max = Math.max(A[i],max);
  8.           if (A[i]<max) {
  9.               max = max-1;
  10.               continue;
  11.           }
  12.           for (int j=1; j<=A[i] && i+j<A.length; j++) {
  13.               f[i+j] = Math.min(f[i+j], f[i]+1);
  14.               if (i+j==A.length-1)
  15.                       return f[i+j];
  16.           }
  17.       }
  18.       return f[A.length-1];
  19.     }
复制代码
回复

使用道具 举报

🔗
 楼主| jaly50 2014-11-26 23:35:08 | 只看该作者
全局:
  1. /*
  2. * LeetCode 124  Flatten Binary Tree to Linked List
  3. * Author: Scarlett Chen
  4. * Date:11/26/2014 Wed 10:32 AM
  5. * in place的意思大概是不要clone tree吧
  6. *  如果我new TreeNode(root.val),就会过不了(1,2)...虽然不知道为什么
  7. *  所以我就先把root的左右孩子先放栈里,然后脱离它与孩子们的关系,再让它放到我的树里。就不复制了。
  8. *  思路:栈,深搜
  9. */


  10. import java.util.Stack;


  11. public class Flatten {
  12.     public void flatten(TreeNode root) {
  13.         TreeNode result;
  14.         TreeNode head = new TreeNode(-1);
  15.         result = head;
  16.         Stack<TreeNode> tree = new Stack<TreeNode>();
  17.         if (root!=null) tree.push(root);
  18.         while (!tree.isEmpty()) {
  19.          root = tree.pop();
  20.         if (root.right!=null) tree.push(root.right);
  21.         root.right = null;
  22.         if (root.left!=null) tree.push(root.left);
  23.         root.left = null;
  24.         result.right = root;
  25.         result.left = null;
  26.         result = result.right;
  27.         }
  28.         root = head.right;
  29.         
  30.     }
  31. }
复制代码
回复

使用道具 举报

🔗
 楼主| jaly50 2014-11-29 15:37:56 | 只看该作者
全局:
  1. /*
  2. * Author: Scarlett
  3. * LeetCode:Insert Interval
  4. * date:11/29/2014 Sat 2:33 AM
  5. * 设(x,y)为newInterval, (a,b)为当前比较的interval
  6. * 要考虑的情况包括: (x<a,y<a);(x<a,a<y<b);(x<a,y>b);(a<x<b,a<y<b);(a<x<b,y>b);(x>b)
  7. * 一开始先把newinterval加进list里
  8. * 注意list不能边改边删,所以要复制list再进行遍历
  9. */
复制代码
  1. /*
  2. * Be careful for the null list~~~!!
  3. * 要想清楚,要分情况!!
  4. */
复制代码
  1.         public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
  2.                 intervals.add(0,newInterval);
  3.                 List<Interval> copy = new LinkedList<Interval>(intervals);
  4.                 Interval pre=newInterval;
  5.                 for (int i=1; i<copy.size(); i++) {
  6.                     Interval list = copy.get(i);
  7.                     if (pre.start < list.start) {
  8.                             if (pre.end < list.start) {
  9.                                     return intervals;
  10.                             }
  11.                             else if (list.start<=pre.end && list.end >=pre.end ) {
  12.                                     list.start = pre.start;
  13.                                     intervals.remove(pre);
  14.                                     return intervals;
  15.                             }
  16.                             else if (pre.end > list.end) {
  17.                                     intervals.remove(list);
  18.                                     continue;
  19.                             }
  20.                     }
  21.                     else if (list.start<=pre.start && list.end>=pre.start) {
  22.                             if (list.start <=pre.end && list.end >=pre.end) {
  23.                                     intervals.remove(pre);
  24.                                     return intervals;
  25.                             }
  26.                             else if (pre.end >list.end) {
  27.                                     pre.start = list.start;
  28.                                     intervals.remove(list);
  29.                                     continue;
  30.                             }
  31.                     }
  32.                     else if (pre.start > list.end) {
  33.                             int a = intervals.indexOf(pre);
  34.                             int b =intervals.indexOf(list);
  35.                             intervals.set(a, list);
  36.                             intervals.set(b, pre);
  37.                             continue;       
  38.                     }
  39.                    
  40.                 }
  41.                 return intervals;
  42.         }
  43.                    
复制代码
回复

使用道具 举报

🔗
 楼主| jaly50 2014-11-29 16:18:52 | 只看该作者
全局:

  1. /*
  2. * 一次过。但是难免边写边改。。如果在白板上写,还需要注意多一些。
  3. * 不喜欢用长名字命名,但是短名字常常含义不清。唉。
  4. * LeetCode 127:Construct Binary Tree from Preorder and Inorder Traversal
  5. * 思路:递归,二分
  6. * Date:11/29/2014 Sat 3:15 AM
  7. *
  8. */
复制代码
  1.    public TreeNode buildTree(int[] preorder, int[] inorder) {
  2.             if (preorder.length==0) return null;
  3.         TreeNode root = new TreeNode(preorder[0]);
  4.         if (preorder.length==1) return root;
  5.         int i=0;
  6.         int[] inorderLeft, inorderRight,preorderLeft,preorderRight;
  7.         //To find the root at int[] inorder, to divide it to two part
  8.         for (int in=0; in<inorder.length; in++) {
  9.             if (inorder[in] == preorder[0])
  10.             { i = in; break;}
  11.         }   
  12.                   inorderLeft = Arrays.copyOfRange(inorder,0,i);
  13.               int leftLen = inorderLeft.length;
  14.               inorderRight = Arrays.copyOfRange(inorder, i+1, inorder.length);
  15.              preorderLeft = Arrays.copyOfRange(preorder, 1,1+leftLen);
  16.              preorderRight = Arrays.copyOfRange(preorder, i+1, preorder.length);
  17.               root.left = buildTree(preorderLeft,inorderLeft);
  18.               root.right = buildTree(preorderRight, inorderRight);
  19.               return root;
  20.          
  21.         }
复制代码
回复

使用道具 举报

🔗
 楼主| jaly50 2014-11-29 16:37:35 | 只看该作者
全局:
  1.         /*
  2.          * 在leetcode上直接写一次过的~
  3.          * 代码也比前一题漂亮多了!
  4.          * 题目是通过后序和中序遍历建树,和前一题基本一样。。
  5.          * LeetCode:Construct Binary Tree from Inorder and Postorder Traversal
  6.          * Date:11/29/2014 Sat 3:37 AM
  7.          * Author:Scarlett
  8.          */
  9.     public TreeNode buildTree(int[] inorder, int[] postorder) {
  10.         int len = inorder.length;
  11.         if (len ==0) return null;
  12.         TreeNode root = new TreeNode(postorder[len-1]);
  13.         if (len==1) return root;
  14.         int indexOfRoot = 0;
  15.         for (int i=0; i<len; i++) {
  16.             if (inorder[i] ==postorder[len-1]) {
  17.                 indexOfRoot = i;
  18.             }
  19.         }
  20.         int[] inorderLeft, inorderRight, postorderLeft, postorderRight;
  21.         inorderLeft = Arrays.copyOfRange(inorder,0,indexOfRoot);
  22.         inorderRight = Arrays.copyOfRange(inorder,indexOfRoot+1,len);
  23.         postorderLeft = Arrays.copyOfRange(postorder,0,indexOfRoot);
  24.         postorderRight = Arrays.copyOfRange(postorder,indexOfRoot,len-1);
  25.         root.left = buildTree(inorderLeft, postorderLeft);
  26.         root.right = buildTree(inorderRight, postorderRight);
  27.         return root;
  28.         
  29.     }
复制代码
回复

使用道具 举报

🔗
 楼主| jaly50 2014-12-13 06:38:43 | 只看该作者
全局:
  1. /*
  2. * LeetCode 136 Validate Binary Search Tree
  3. * Author: Scarlett
  4. * 这道题很容易陷入一个小陷阱,就是只测试是否root.left <root<root.right,但其实BST的要求是必须root.left的最右儿子也要小于root的值。
  5. * 所以一开始写了fail的版本。
  6. *
  7. *  后来想着用DFS来做,每次记录前一个访问过的结点的值,必须小于当前结点。就可以满足BST的条件了。
  8. *  但是前一个访问过的点的值pre,在每个访问点上 从call左子树到call右子树之间是会变化的。
  9. *  因此又想了很久要怎么储存,进入了一些误区,还考虑过了应该是primitive or reference...要不要static...
  10. */


  11. public class IsValidBST {
  12.         Long pre;
  13.         public boolean isValidBST(TreeNode root) {
  14.                 if (root ==null) return true;
  15.                 boolean ans = true;
  16.                 pre = new Long((long)(Integer.MIN_VALUE) -1);
  17.                 return isValidNode(root, ans);

  18.         }
  19.         private boolean isValidNode(TreeNode root, boolean ans) {
  20.                 if (!ans) return ans;
  21.                 //System.out.println("At first, root= "+root.val+" pre= "+pre);
  22.                 if (root.left!=null) ans &= isValidNode(root.left,ans);
  23.                 if (pre < root.val) {
  24.                         pre =new Long(root.val);
  25.                 }
  26.                 else return false;
  27.                 //System.out.println("root= "+root.val+" pre= "+pre);
  28.                 if (root.right!=null) ans &= isValidNode(root.right,ans);
  29.                 //System.out.println("root= "+root.val+" pre= "+pre);
  30.                 return ans;
  31.         }

  32.         public boolean isValidBST_fail(TreeNode root) {
  33.                 if (root == null) return true;
  34.                 boolean ans = true;
  35.                 if (root.left !=null) {
  36.                     ans &= isValidBST(root.left);
  37.                     ans &= root.val > root.left.val;
  38.                 }
  39.                 if (root.right !=null) {
  40.                     ans &= isValidBST(root.right);
  41.                     ans &= root.val < root.right.val;
  42.                 }
  43.                 return ans;
  44.             }
  45.         public static void main(String[] args) {
  46.                 // TODO Auto-generated method stub
  47.                 IsValidBST is = new IsValidBST();
  48.         TreeNode root = new TreeNode(3);
  49.         TreeNode a = new TreeNode(1);
  50.         TreeNode b = new TreeNode(2);
  51.         TreeNode c = new TreeNode(4);
  52.         root.left = a;
  53.         root.right = c;
  54.         a.right = b;
  55.         System.out.println(is.isValidBST(root));
  56.         }

  57. }
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表