LC合并两个有序链表
//想到了双指针的写法,但是循环条件应该是两个都不为空才可以进入循环,之后再判断哪一个指针为空,那么拼接另外一个链表到后面即可
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
//循环迭代
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(-1);
ListNode cur = dummy;
while(l1 != null && l2 != null){
if(l1.val < l2.val){
cur.next = new ListNode(l1.val);
l1 = l1.next;
}else{
cur.next = new ListNode(l2.val);
l2 = l2.next;
}
cur = cur.next;
}
cur.next = l1 == null ? l2 : l1;
return dummy.next;
}
}
//递归算法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null) return l2;
if(l2 == null) return l1;
if(l1.val < l2.val){
l1.next = mergeTwoLists(l1.next,l2);
return l1;
}else{
l2.next = mergeTwoLists(l1,l2.next);
return l2;
}
}
}
LC173. 二叉搜索树迭代器
//其实就是将二叉搜索树的中序遍历进行拆解,hasNext其实就是中序遍历的while循环条件,next其实就是循环体的内容,定义一个全局变量cur和栈,维护一个实时的栈即可。如果提前遍历保存到list中也可以,这样的话空间复杂度直接就是n,而维护一个实时的栈不一定是n。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class BSTIterator {
TreeNode cur;
Deque<TreeNode> stack;
public BSTIterator(TreeNode root) {
cur = root;
stack = new LinkedList<TreeNode>();
}
public int next() {
while(cur != null){
stack.push(cur);
cur = cur.left;
}
cur = stack.pop();
int res = cur.val;
cur = cur.right;
return res;
}
public boolean hasNext() {
return cur != null || !stack.isEmpty();
}
}
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator obj = new BSTIterator(root);
* int param_1 = obj.next();
* boolean param_2 = obj.hasNext();
*/
LC404. 左叶子之和
//首先广度优先遍历使用队列比较好做,主要是在想如何使用递归进行运算.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
return dfs(root);
}
public int dfs(TreeNode root){
int ans = 0;
if(root.left != null){
ans += isLeaf(root.left) ? root.left.val : dfs(root.left);
}
if(root.right != null && !isLeaf(root.right)){
ans += dfs(root.right);
}
return ans;
}
public boolean isLeaf(TreeNode root){
return root.left == null && root.right == null;
}
}