2. Add Two Numbers
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.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
/**
* Definition for singly-linked list.* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int sum=0;
ListNode temp1=l1;
ListNode temp2=l2;
ListNode result = new ListNode(0);
ListNode resultTemp = result;
ListNode temp=resultTemp;
while((temp1!=null) || (temp2 !=null)){
sum=((temp1 != null) ? temp1.val:0) + ((temp2 != null) ? temp2.val:0) + resultTemp.val;
if(sum>9){
sum = sum -10;
resultTemp.next = new ListNode(1);
}
else{
resultTemp.next = new ListNode(0);
}
resultTemp.val = sum;
temp=resultTemp;
resultTemp = resultTemp.next;
temp1 = (temp1 !=null)?temp1.next:temp1;
temp2 = (temp2 !=null)?temp2.next:temp2;
}
temp.next=(temp.next.val==0)?null:temp.next;
return result;
}
}
94. Binary Tree Inorder Traversal
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree [1,null,2,3]
,
1 \ 2 / 3
return [1,3,2]
.
public List < Integer > inorderTraversal(TreeNode root) {
List < Integer > res = new ArrayList < > (); //泛型
helper(root, res);//递归地调用方法
return res;
}
//先判断root是否为null,非null则先递归进入左子树,然后访问root,最后递归进入右子树;
public void helper(TreeNode root, List < Integer > res) {
if (root != null) {
if (root.left != null) {helper(root.left, res);
}
res.add(root.val);
if (root.right != null) {
helper(root.right, res);
}
}
}
}
方法二:使用非递归方法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List <Integer> res = new ArrayList <> ();
TreeNode bt = root;
Stack <TreeNode> stack = new Stack <> ();
while(bt != null || !stack.isEmpty()){
while(bt != null){
stack.push(bt);
bt = bt.left;
}
if(!stack.isEmpty()){
bt = stack.pop();
res.add(bt.val);
bt = bt.right;
}
}
return res;
}
}
96. Unique Binary Search Trees
Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
For example,
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
class Solution {
public int numTrees(int n) {
int[] sum = new int[n+1];
int ssum = 0;
sum[0]=1;
sum[1]=1;
for(int i =2;i<=n;i++){
ssum = 0;
for(int j=0; j<i/2;j++){
ssum += sum[j]*sum[i-1-j];
}
if(i%2==0){
sum[i]=ssum*2;
}
else{
sum[i]=ssum*2+sum[i/2]*sum[i-1-i/2];
}
}
return sum[n];
}
}
20. Valid Parentheses
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
The brackets must close in the correct order, "()"
and "()[]{}"
are all valid but "(]"
and "([)]"
are not.
class Solution {
public boolean isValid(String s) {
Stack <Character>stack = new Stack<Character>();
for(int i =0;i<s.length();i++){
if(s.charAt(i) == '('){
stack.push(')');
continue;
}
if(s.charAt(i) == '['){
stack.push(']');
continue;
}
if(s.charAt(i) == '{'){
stack.push('}');
continue;
}
if(stack.isEmpty()||stack.pop() != s.charAt(i))
return false;
}
if(!stack.isEmpty())
return false;
return true;
}
}
95. Unique Binary Search Trees II
Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1...n.
For example,
Given n = 3, your program should return all 5 unique BST's shown below.
1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<TreeNode> generateTrees(int n) {
if (n==0){
return new ArrayList();
}
return helper(1,n);
}
public List<TreeNode> helper(int k,int n){
List<TreeNode> res = new ArrayList<>();
if(n==k){
res.add(new TreeNode(k));
return res;
}
if(n<k){
res.add(null);
return res;
}
TreeNode root;
for(int i=k;i<=n;i++){
for(TreeNode left : helper(k,i-1)){
for(TreeNode right : helper(i+1,n)){
root = new TreeNode(i);
root.left = left;
root.right =right;
res.add(root);
}
}
}
return res;
}
}
方法二:性能更好
思路介绍:root是将n-1的各棵树添加到以n为根节点的树上,rootChg则是逐渐将n这个节点往n-1的各棵树深层次移,移动是沿着树的右节点移动,直到移动到树的最右叶节点。注意的地方是要不断的深复制n-1的各棵树。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<TreeNode> generateTrees(int n) {
if (n==0){
return new ArrayList();
}
List<TreeNode> res = new ArrayList<>();
TreeNode root;
TreeNode temp;
TreeNode rootChg;
res.add(null);
for(int len =1;len <= n;len++){
List<TreeNode> res2 = new ArrayList<>();
for (TreeNode node: res){
root = new TreeNode(len);
root.left = node;
res2.add(root);
temp = node;
while(temp!=null){
rootChg = copytree(node);
TreeNode rootChgTemp = rootChg;
while(rootChgTemp.val != temp.val){
rootChgTemp = rootChgTemp.right;
}
rootChgTemp.left = temp.left;
rootChgTemp.right = new TreeNode(len);
rootChgTemp.right.left = temp.right;
res2.add(rootChg);
temp = temp.right;
}
}
res =res2;
}
return res;
}
private TreeNode copytree(TreeNode root){
if(root == null) return null;
TreeNode croot = new TreeNode(root.val);
croot.left = copytree(root.left);
croot.right = copytree(root.right);
return croot;
}
}
98. Validate Binary Search Tree
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:
2 / \ 1 3Binary tree
[2,1,3]
, return true.
Example 2:
1 / \ 2 3
Binary tree [1,2,3]
, return false.
方法一:递归解法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isValidBST(TreeNode root) {
return isValidBSTHelper(root,null,null);
}
private boolean isValidBSTHelper(TreeNode root,Integer min, Integer max){
if(root == null)
return true;
if(root.left != null && root.left.val >= root.val)
return false;
if(root.right != null && root.right.val <= root.val)
return false;
if(min != null && root.left != null && root.left.val <= min)
return false;
if(max != null && root.right != null && root.right.val >= max)
return false;
return isValidBSTHelper(root.left,min,root.val) && isValidBSTHelper(root.right,root.val,max);
}
}
方法二:中序遍历法
class Solution {
public boolean isValidBST(TreeNode root) {
if(root == null){
return true;
}
Stack<TreeNode> stackVal = new Stack<>();
Integer pre = null;
while(root != null || !stackVal.isEmpty()){
while(root != null){
stackVal.push(root);
root = root.left;
}
root = stackVal.pop();
if(pre != null && root.val <= pre) return false;
pre = root.val;
root = root.right;
}
return true;
}
}