剑指offer-day15
二叉树中和为某一值的路径
完全没思路,直接放答案。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
class Solution { LinkedList<Integer> path = new LinkedList<>(); LinkedList<List<Integer>> res = new LinkedList<>(); public List<List<Integer>> pathSum(TreeNode root, int target) { firstOrder(root,target); return res; }
public void firstOrder(TreeNode root, int target){ if(root == null){ return; } path.add(root.val); target -= root.val; if(target == 0 && root.left == null && root.right == null){ res.add(new LinkedList(path)); } pathSum(root.left,target); pathSum(root.right,target); path.removeLast(); } }
|
二叉搜索树与双向链表
这道题想到了中序遍历,但是对双链表还是不太熟悉,没做出来,半抄了一个答案。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
class Solution { Node head; Node pre; public Node treeToDoublyList(Node root) { if(root == null){ return null; } inorder(root); head.left = pre; pre.right = head; return head; }
public void inorder(Node root){ if(root == null){ return; } inorder(root.left); if(pre != null){ pre.right = root; } else{ head = root; } root.left = pre; pre = root; inorder(root.right); } }
|
二叉搜索树的第k大节点
这道题倒是写出来了,但是还是老问题,时空复杂度非常感人,看了答案发现用了一个逆序的中序遍历,而且提前终止了遍历,所以能有非常优秀的时空复杂度。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
class Solution { int res; int k; public int kthLargest(TreeNode root, int k) { this.k = k; inorder(root); return res; }
public void inorder(TreeNode root){ if(root == null || k == 0){ return; }
inorder(root.right); if(--k == 0){ res = root.val; } inorder(root.left); } }
|