leetcode 1-100

1. Two Sum (easy)

找到数组中和为target的两个数,返回索引

problem
View Code

 


2. Add Two Numbers (medium)

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

      Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
      Output: 7 -> 0 -> 8

用链表表示十进制数(反向),求两个数的和;

View Code

 


 

3. Longest Substring Without Repeating Characters (medium)

最长的无重复的子字符串

problem
View Code

 


4. Median of Two Sorted Arrays (hard)

找到两个排序好的数组的中位数

problem
View Code

 


5. Longest Palindromic Substring (medium)

最长的对称子字符串

problem
View Code

 


6. ZigZag Conversion (medium)

以zigzag顺序重排字符串

problem
View Code

 


7. Reverse Integer (easy)

反转数字

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321
Example 2:

Input: -123
Output: -321
Example 3:

Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  2311]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
problem
 1 class Solution {
 2 public:
 3     int reverse(int x) {
 4         int result = 0;
 5         while (x != 0) {
 6             int temp = result*10 + x%10;
 7             if (temp/10 != result)   // 处理越界
 8                 return 0;
 9             result = temp;
10             x /= 10;
11         }
12         return result;
13     }
14 };
View Code

 


8. String to Integer (atoi) (medium)

字符串转数字

problem
View Code

 


 

10. Regular Expression Matching (hard) #

正则表达式匹配:.和*

problem
View Code
View Code

 


9. Palindrome Number (easy)

判断数字是否为回文

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

Input: 121
Output: true
Example 2:

Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:

Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:

Coud you solve it without converting the integer to a string?
problem
 1 class Solution {
 2 public:
 3     bool isPalindrome(int x) {
 4         if (x < 0 || (x != 0 && x%10 == 0)) return false;
 5         int orig = x;
 6         long reverse = 0;
 7         while (x > reverse) {
 8             reverse = reverse*10 + x%10;
 9             x /= 10;
10         }
11         return x == reverse || x == reverse/10;
12     }
13 };
View Code

 


10. Regular Expression Matching (hard) #

正则表达式匹配:.和*

problem
View Code
View Code

 


11. Container With Most Water (medium)

 数组中每个元素代表容器一边的高度,两元素的距离代表容器的宽度,找到两个边使容器容量最高

problem
View Code

 


12. Integer to Roman (medium)

数字转罗马数字

problem
View Code

 


13. Roman to Integer (easy)

罗马数字转普通数字

problem
View Code

 


14. Longest Common Prefix (easy)

最长的公共前缀

problem
View Code

 


15. 3 Sum (medium)

 找到数组中所有的 和为0的 三元数组。

problem
View Code

 


16. 3Sum Closest (medium)

 找到距离target最近的三元数组,返回三个数的和

problem
View Code

 


17. Letter Combinations of a Phone Number (medium) #

手机键盘输入组合

problem
View Code

 


18. 4Sum (medium)

找到所有和为target的四元数组

problem
View Code

 


19. Remove Nth Node From End of List (medium)

Given a linked list, remove the nth node from the end of list and return its head.

For example,

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.

Note: 
Given n will always be valid.

移除链表中的倒数第N个节点

View Code

 


20. Valid Parentheses (easy)

判断()[]{}格式

problem
View Code

 


21. Merge Two Sorted Lists (easy)

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

View Code

 


22. Generate Parentheses (medium) #

n个括号对的所有组合

problem
View Code

 


23. Merge k Sorted Lists (hard) #

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

View Code

 


24. Swap Nodes in Pairs (medium)#

Given a linked list, swap every two adjacent nodes and return its head.

For example

Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

把链表中每两个元素进行反转

View Code

 


25. Reverse Nodes in k-Group (hard)#

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. 
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

For example,

Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5

每k个元素进行一次反转链表,返回总链表头

View Code
View Code

 


26. Remove Duplicates from Sorted Array (easy)

把不重复的元素放在数组最前面,返回不重复元素个数

problem
View Code

 


27. Remove Element (easy)

 把不等于val的数放在数组的前面,返回其个数

problem
View Code

 


28. Implement strStr() (easy)

字符串查找

problem
View Code

 


29. Divide Two Integers (medium)

不用除号计算除法

Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.

Return the quotient after dividing dividend by divisor.

The integer division should truncate toward zero.

Example 1:

Input: dividend = 10, divisor = 3
Output: 3
Example 2:

Input: dividend = 7, divisor = -3
Output: -2
Note:

Both dividend and divisor will be 32-bit signed integers.
The divisor will never be 0.
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  2311]. For the purpose of this problem, assume that your function returns 2311 when the division result overflows.
problem
 1 class Solution {
 2 public:
 3     int divide(int dividend, int divisor) {
 4         if (dividend == INT_MIN && divisor == -1) return INT_MAX;
 5         long long a = labs(dividend);                   // abs在处理(-2147483648,1)时出错
 6         long long b = labs(divisor);
 7         int res = 0;
 8         while (a >= b) {
 9             long long temp = b;
10             long long mult = 1;
11             while (a >= (temp << 1)) {                  // 第一版写成了(a >= temp)
12                 temp <<= 1;
13                 mult <<= 1;
14             }
15             res += mult;
16             a -= temp;
17         }
18         return (dividend < 0)^(divisor < 0) ? -res : res;
19     }
20 };
View Code

 


30. Substring with Concatenation of All Words (hard) #

查找字符串,子串为words的组合

problem
View Code

 


31. Next Permutation (medium)

下一个排列:nums中的数字组成的数中,比 以原顺序组成的 大的下一个数组

problem
View Code

 


32. Longest Valid Parentheses (hard) #

最长的有效括号

problem
View Code
View Code

 


33. Search in Rotated Sorted Array (medium) #

在一个旋转后的有序数列中找到target

problem
View Code

 


34. Search for a Range (medium)

 找到有序数组中值为target的索引范围

problem
View Code

 


35. Search Insert Position (easy)

 有序数组中找target的位置,如果没有,找到应该插入的位置

problem
View Code

 


36. Valid Sudoku (medium) #

判断数独矩阵是否有效

problem
View Code

 


37. Sudoku Solver (hard) #

解出数独答案

problem
View Code
View Code

 


38. Count and Say (easy)

数字字符串描述

problem
View Code

 


39. Combination Sum (medium)

 找到数组中所有和为target的组合,数可以重复使用,数组中无重复元素

problem
View Code

 


40. Combination Sum II (medium)

找到数组中所有和为target的组合,每个数只能取一次,数组中有重复元素

problem
View Code

 


41. First Missing Positive (hard) #

找到数组中第一个丢失的正整数

problem
View Code

 


42. Trapping Rain Water (hard) #

水容量

problem
View Code

 


43. Multiply Strings (medium)

字符串代表的两个数相乘,返回字符串

problem
View Code

 


44. Wildcard Matching (hard) #

通配正则表达式:*和?

problem
View Code
View Code
error code

 


45. Jump Game II (hard) #

跳步问题:数组中的数表示在当前位置可以跳跃的长度,计算从头到尾最少的跳跃步数

problem
View Code

 


46. Permutations (medium) #

数组的所有乱序组合

Given a collection of distinct integers, return all possible permutations.

Example:

Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]
problem
 1 // 使用swap,省去了一个tmp
 2 class Solution {
 3 public:
 4     vector<vector<int>> permute(vector<int>& nums) {
 5         vector<vector<int>> res;
 6         backtracking(nums, res, 0, nums.size());
 7         return res;
 8     }
 9     void backtracking(vector<int>& nums, vector<vector<int>>& res, int start, int end) {
10         if (start >= end) {
11             res.push_back(nums);
12             return;
13         }
14         for (int i = start; i < end; ++i) {
15             swap(nums[start], nums[i]);
16             backtracking(nums, res, start + 1, end);
17             swap(nums[start], nums[i]);
18         }
19     }
20 };
View Code
 1 // 迭代:在上一次的结果中的各个位置插入新元素
 2 public List<List<Integer>> permute(int[] num) {
 3     List<List<Integer>> ans = new ArrayList<List<Integer>>();
 4     if (num.length ==0) return ans;
 5     List<Integer> l0 = new ArrayList<Integer>();
 6     l0.add(num[0]);
 7     ans.add(l0);
 8     for (int i = 1; i< num.length; ++i){
 9         List<List<Integer>> new_ans = new ArrayList<List<Integer>>(); 
10         for (int j = 0; j<=i; ++j){            
11            for (List<Integer> l : ans){
12                List<Integer> new_l = new ArrayList<Integer>(l);
13                new_l.add(j,num[i]);
14                new_ans.add(new_l);
15            }
16         }
17         ans = new_ans;
18     }
19     return ans;
20 }
View Code

 


47. Permutations II (medium) #

数组的所有乱序组合,数组内包含重复数字

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

Example:

Input: [1,1,2]
Output:
[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]
problem
 1 class Solution {
 2 public:
 3     vector<vector<int>> permuteUnique(vector<int>& nums) {
 4         vector<vector<int>> res;
 5         sort(nums.begin(), nums.end());
 6         backtracking(nums, res, 0, nums.size());
 7         return res;
 8     }
 9     void backtracking(vector<int> nums, vector<vector<int>>& res, int start, int end) {
10         if (start == end - 1) {
11             res.push_back(nums);
12             return;
13         }
14         for (int i = start; i < end; ++i) {
15             if (i != start && nums[i] == nums[start])
16                 continue;
17             swap(nums[start], nums[i]);
18             backtracking(nums, res, start + 1, end);
19             //swap(nums[start], nums[i]);
20         }
21     }
22 };
View Code
 1 // 迭代(java)
 2 public class Solution {
 3     public List<List<Integer>> permuteUnique(int[] nums) {
 4         List<List<Integer>> res = new ArrayList<List<Integer>>();
 5         if(nums==null || nums.length==0) return res;
 6         boolean[] used = new boolean[nums.length];
 7         List<Integer> list = new ArrayList<Integer>();
 8         Arrays.sort(nums);
 9         dfs(nums, used, list, res);
10         return res;
11     }
12 
13     public void dfs(int[] nums, boolean[] used, List<Integer> list, List<List<Integer>> res){
14         if(list.size()==nums.length){
15             res.add(new ArrayList<Integer>(list));
16             return;
17         }
18         for(int i=0;i<nums.length;i++){
19             if(used[i]) continue;
20             if(i>0 &&nums[i-1]==nums[i] && !used[i-1]) continue;
21             used[i]=true;
22             list.add(nums[i]);
23             dfs(nums,used,list,res);
24             used[i]=false;
25             list.remove(list.size()-1);
26         }
27     }
28 }
View Code

 


48. Rotate Image (medium)

 旋转方阵

problem
View Code

 


49. Group Anagrams (medium)

字符串分组,组成元素一致的分为一组

problem
View Code

 


50. Pow(x, n) (medium)

实现指数函数

Implement pow(x, n), which calculates x raised to the power n (xn).

Example 1:

Input: 2.00000, 10
Output: 1024.00000
Example 2:

Input: 2.10000, 3
Output: 9.26100
Example 3:

Input: 2.00000, -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
Note:

-100.0 < x < 100.0
n is a 32-bit signed integer, within the range [−231, 2311]
problem
 1 class Solution {
 2 public:
 3     double myPow(double x, int n) {
 4         if(n==0) return 1;
 5         if (abs(x) > 1 && n == INT_MIN) return 0;
 6         if(n<0){
 7             n = -n;
 8             x = 1/x;
 9         }
10         return n%2==0 ? myPow(x*x, n/2) : x*myPow(x*x, n/2);
11     }
12 };
View Code

 


51. N-Queens (hard)

n皇后问题,输出所有情况

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.

Example:

Input: 4
Output: [
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.
problem

 1 class Solution {
 2 public:
 3     vector<vector<string>> solveNQueens(int n) {
 4         vector<vector<string>> res;
 5         vector<string> tmp(n, string(n, '.'));
 6         vector<bool> col(n, false), left(2*n - 1, false), right(2*n - 1, false);
 7         backtracking(res, col, left, right, 0, tmp, n);
 8         return res;
 9     }
10     void backtracking(vector<vector<string>>& res, vector<bool>& col, vector<bool>& left, vector<bool>& right, int row, vector<string>& tmp, int n) {
11         if (row == n) {
12             res.push_back(tmp);
13             return;
14         }
15         for (int i = 0; i < n; ++i) {
16             if ((!col[i]) && (!left[row + i]) && (!right[i - row + n - 1])) {
17                 tmp[row][i] = 'Q';
18                 col[i] = true;
19                 left[row + i] = true;
20                 right[i - row + n - 1] = true;
21                 backtracking(res, col, left, right, row + 1, tmp, n);
22                 col[i] = false;
23                 left[row + i] = false;
24                 right[i - row + n - 1] = false;
25                 tmp[row][i] = '.';
26             }
27         }
28     }
29 };
View Code

 


52. N-Queens II (hard)

n皇后问题,只输出解的个数

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return the number of distinct solutions to the n-queens puzzle.

Example:

Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]
problem
 1 class Solution {
 2 public:
 3     int totalNQueens(int n) {
 4         int res = 0;
 5         vector<bool> col(n, false), left(2*n - 1, false), right(2*n - 1, false);
 6         backtracking(res, col, left, right, 0, n);
 7         return res;
 8     }
 9     void backtracking(int& res, vector<bool>& col, vector<bool>& left, vector<bool>& right, int row, int n) {
10         if (row == n) {
11             ++res;
12             return;
13         }
14         for (int i = 0; i < n; ++i) {
15             if ((!col[i]) && (!left[row + i]) && (!right[i - row + n - 1])) {
16                 col[i] = left[row + i] = right[i - row + n - 1] = true;
17                 backtracking(res, col, left, right, row + 1, n);
18                 col[i] = left[row + i] = right[i - row + n - 1] = false;
19             }
20         }
21     }
22 };
View Code

 


53. Maximum Subarray (easy)

使数组中连续的数的和最大,返回和

problem
View Code

 


54. Spiral Matrix (medium)

 以旋转的顺序将矩阵转换为数组

problem
View Code

 


55. Jump Game (medium)

跳步问题:数组中的数表示在当前位置可以跳跃的长度,判断是否能到达数组尾部

problem
View Code

 


56. Merge Intervals (medium)

 合并区间:把有重复的区间合并成一个

problem
View Code

 


57. Insert Interval (hard)

 在无重复的区间列表中插入一个区间,并合并重复的区间

problem
View Code

 


58. Length of Last Word (easy)

字符串中最后一个单词的长度

problem
View Code

 


59. Spiral Matrix II (medium)

以旋转的顺序将1~n*n填写到方阵中

problem
View Code

 


61. Rotate List (medium)#

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:

Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

使链表循环右移k次

View Code

 


62. Unique Paths (medium)

从(1, 1)到(m, n)的路径个数

problem
View Code

 


63. Unique Paths II (medium)

 从(1, 1)到(m, n)的路径个数,给定矩阵中1代表不能通行

problem
View Code

 


64. Minimum Path Sum (medium)

  从矩阵左上到右下,使路径上的和最小

problem
View Code

 


65. Valid Number (hard)

判断字符串是不是一个数字(题不好,没仔细看)

problem
View Code

 


66. Plus One (easy)

用数组代表一个数,让这个数加一,返回数组

problem
View Code

 


67. Add Binary (easy)

字符串表示的两个二进制数相加

problem
View Code

 


68. Text Justification (hard) #

文本两端对齐

problem
View Code

 


71. Simplify Path (medium) #

简化unix路径文本

problem
View Code

 


72. Edit Distance (hard)

一个word经过增、删、该,最少几步到另一个word

problem
View Code

 


73. Set Matrix Zeroes (medium)

如果矩阵中有元素是0,就把同一行和同一列全置为0

problem
View Code

 


74. Search a 2D Matrix (medium)

在排好序的二维数组中查找target

problem
View Code

 


75. Sort Colors (medium)

数组中只有0,1,2;排序数组

problem
View Code

 


76. Minimum Window Substring (hard) #

最小的包含某子串的窗口

problem
View Code

 


78. Subsets (medium)

 无重复的数组的所有子集

problem
View Code
View Code

 


79. Word Search (medium)

矩阵中找字符串

problem
View Code

 


80. Remove Duplicates from Sorted Array II (medium) #

删除重复的元素,使每个元素最多有两个

problem
View Code

 


81. Search in Rotated Sorted Array II (medium) #

在一个旋转后的有序数列中找到target,数列中有可能存在重复元素

problem
View Code

 


82. Remove Duplicates from Sorted List II (medium)

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,

Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

移除链表中重复的元素

View Code

 


83. Remove Duplicates from Sorted List (easy)

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,

Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

移除链表中重复的元素,保留一个

View Code

 


84. Largest Rectangle in Histogram (hard) #

problem
View Code

 


85. Maximal Rectangle (hard) #

 找到矩阵中,最大的 值全为1的子矩阵

problem
View Code
View Code

 


 

86. Partition List (medium)

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

For example,

Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

 把小于x的移到左边,两边保持原顺序不变

View Code

 


87. Scramble String (hard)

旋转单词:判断一个单词是否由另一个单词多次旋转得到

problem
View Code

 


88. Merge Sorted Array (easy)

合并排好序的数列

probelm
View Code

 


90. Subsets II (medium)

有重复元素的数组的子集

problem
View Code
View Code
View Code

 


91. Decode Ways (hard) #

把数字序号解析为字母的方式数量

problem
View Code

 


92. Reverse Linked List II (medium)

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:

Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.

反转链表中第m到n个元素

View Code

 


93. Restore IP Addresses (medium)

把字符串解析为IP地址

problem
View Code

 


94. Binary Tree Inorder Traversal (medium)

二叉树的中序遍历

problem
View Code

 


95. Unique Binary Search Trees II (medium) #

把所有<=n的整数组成BST,输出所有可能的结果

Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n.

Example:

Input: 3
Output:
[
  [1,null,3,2],
  [3,2,null,1],
  [3,1,null,null,2],
  [2,1,3],
  [1,null,2,null,3]
]
Explanation:
The above output corresponds to the 5 unique BST's shown below:

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3
problem
 1 递归:小于i的值组成的树一定在i的左节点,递归调用,生成所有左右子树的组合
 2 /**
 3  * Definition for a binary tree node.
 4  * struct TreeNode {
 5  *     int val;
 6  *     TreeNode *left;
 7  *     TreeNode *right;
 8  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 9  * };
10  */
11 class Solution {
12 public:
13     vector<TreeNode*> generateTrees(int n) {
14         vector<TreeNode*> ret;
15         return n == 0 ? ret : func(1, n);
16     }
17 
18     vector<TreeNode*> func(int start, int end) {
19         vector<TreeNode*> ret;
20         if (start > end) ret.push_back(NULL);
21         for (int i = start; i <= end; ++i) {
22             vector<TreeNode*> left = func(start, i - 1);
23             vector<TreeNode*> right = func(i + 1, end);
24             for (auto l : left) {
25                 for (auto r : right) {
26                     TreeNode* root = new TreeNode(i);
27                     root -> left = l;
28                     root -> right = r;
29                     ret.push_back(root);
30                 }
31             }
32         }
33         return ret;
34     }
35 };
View Code

 


96. Unique Binary Search Trees (medium) #

把所有<=n的整数组成BST,输出结果的个数

Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?

Example:

Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3
problem
 1 // 思路类似95,但不需要递归,只需把n个数字可组成BST的个数记录下来即可,类似DP。
 2 class Solution {
 3 public:
 4     int numTrees(int n) {
 5         vector<int> res(n + 1, 0);
 6         res[0] = res[1] = 1;
 7         for (int i = 2; i <= n; ++i) {
 8             for (int j = 1; j <= i; ++j) {
 9                 res[i] += res[j - 1]*res[i - j];
10             }
11         }
12         return res[n];
13     }
14 };
View Code

 


97. Interleaving String (hard)

判断两个字符串是否能组合成另一个字符串

problem
View Code

 


98. Validate Binary Search Tree (medium)

判断一个树是否符合BST

Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
Example 1:

Input:
    2
   / \
  1   3
Output: true
Example 2:

    5
   / \
  1   4
     / \
    3   6
Output: false
Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value
             is 5 but its right child's value is 4.
problem
 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     TreeNode* pre = NULL;
13     bool isValidBST(TreeNode* root) {
14         if (!root) return true;
15         if (!isValidBST(root -> left)) return false;
16         if (pre && root -> val <= pre -> val) return false;
17         pre = root;
18         return isValidBST(root -> right);
19     }
20 };
View Code

 


99. Recover Binary Search Tree (hard) #

BST中有两个元素替换位置了,找出来并恢复

Two elements of a binary search tree (BST) are swapped by mistake.

Recover the tree without changing its structure.

Example 1:

Input: [1,3,null,null,2]

   1
  /
 3
  \
   2

Output: [3,1,null,null,2]

   3
  /
 1
  \
   2
Example 2:

Input: [3,1,4,null,null,2]

  3
 / \
1   4
   /
  2

Output: [2,1,4,null,null,3]

  2
 / \
1   4
   /
  3
Follow up:

A solution using O(n) space is pretty straight forward.
Could you devise a constant space solution?
problem
 1 public class Solution {
 2     
 3     TreeNode firstElement = null;
 4     TreeNode secondElement = null;
 5     // The reason for this initialization is to avoid null pointer exception in the first comparison when prevElement has not been initialized
 6     TreeNode prevElement = new TreeNode(Integer.MIN_VALUE);
 7     
 8     public void recoverTree(TreeNode root) {
 9         
10         // In order traversal to find the two elements
11         traverse(root);
12         
13         // Swap the values of the two nodes
14         int temp = firstElement.val;
15         firstElement.val = secondElement.val;
16         secondElement.val = temp;
17     }
18     
19     private void traverse(TreeNode root) {
20         
21         if (root == null)
22             return;
23             
24         traverse(root.left);
25         
26         // Start of "do some business", 
27         // If first element has not been found, assign it to prevElement (refer to 6 in the example above)
28         if (firstElement == null && prevElement.val >= root.val) {
29             firstElement = prevElement;
30         }
31     
32         // If first element is found, assign the second element to the root (refer to 2 in the example above)
33         if (firstElement != null && prevElement.val >= root.val) {
34             secondElement = root;
35         }        
36         prevElement = root;
37 
38         // End of "do some business"
39 
40         traverse(root.right);
41 }
View Code
Morris Traversal

 


100. Same Tree (easy)

判断两个树完全相同

Given two binary trees, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

Example 1:

Input:     1         1
          / \       / \
         2   3     2   3

        [1,2,3],   [1,2,3]

Output: true
Example 2:

Input:     1         1
          /           \
         2             2

        [1,2],     [1,null,2]

Output: false
Example 3:

Input:     1         1
          / \       / \
         2   1     1   2

        [1,2,1],   [1,1,2]

Output: false
problem
 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     bool isSameTree(TreeNode* p, TreeNode* q) {
13         
14         if (!p || !q) return (p == q);
15         return (p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right));
16     }
17 };
View Code

 

 

 

 

 

 

 

#

posted @ 2018-08-02 21:14  zz091207  阅读(176)  评论(0编辑  收藏  举报