[关闭]
@Yano 2019-09-20T02:51:52.000000Z 字数 34071 阅读 6129

LeetCode Tree 题目汇总(前 500 题)

LeetCode


https://www.zybuluo.com/Yano/note/1009816

94 Binary Tree Inorder Traversal

https://leetcode.com/problems/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].

Note: Recursive solution is trivial, could you do it iteratively?

代码

  1. public List<Integer> inorderTraversal(TreeNode root) {
  2. List<Integer> ans = new ArrayList<>();
  3. robot(root, ans);
  4. return ans;
  5. }
  6. private void robot(TreeNode root, List<Integer> ans) {
  7. if(root == null) return;
  8. robot(root.left, ans);
  9. ans.add(root.val);
  10. robot(root.right, ans);
  11. }
  1. public class Solution {
  2. public List<Integer> inorderTraversal(TreeNode r) {
  3. List<Integer> ans = new ArrayList<Integer>();
  4. List<TreeNode> vector = new ArrayList<TreeNode>();
  5. while(vector.size() != 0 || r != null){
  6. // 一直放入左儿子(左)
  7. while(r != null) {
  8. vector.add(r);
  9. r = r.left;
  10. }
  11. // 访问当前元素(中),把右儿子入栈(右)
  12. if(vector.size() != 0) {
  13. r = vector.get(vector.size() - 1);
  14. vector.remove(vector.size() - 1);
  15. ans.add(r.val);
  16. r = r.right;
  17. }
  18. }
  19. return ans;
  20. }
  21. }

144 Binary Tree Preorder Traversal

https://leetcode.com/problems/binary-tree-preorder-traversal/

题目描述

Given a binary tree, return the preorder traversal of its nodes' values.

For example:
Given binary tree [1,null,2,3],

   1
    \
     2
    /
   3

return [1,2,3].

Note: Recursive solution is trivial, could you do it iteratively?

代码

  1. public class Solution {
  2. public List<Integer> preorderTraversal(TreeNode root) {
  3. List<Integer> ans = new ArrayList<Integer>();
  4. List<TreeNode> vector = new ArrayList<TreeNode>();
  5. vector.add(root);
  6. while(vector.size() != 0) {
  7. TreeNode tmp = vector.get(vector.size() - 1);
  8. vector.remove(vector.size() - 1);
  9. if(tmp != null) {
  10. ans.add(tmp.val);
  11. vector.add(tmp.right);
  12. vector.add(tmp.left);
  13. }
  14. }
  15. return ans;
  16. }
  17. }

145 Binary Tree Postorder Traversal

https://leetcode.com/problems/binary-tree-postorder-traversal/

题目描述

Given a binary tree, return the postorder traversal of its nodes' values.

For example:
Given binary tree {1,#,2,3},

   1
    \
     2
    /
   3

return [3,2,1].

Note: Recursive solution is trivial, could you do it iteratively?

代码

  1. public class Solution {
  2. public static class StackNode {
  3. TreeNode root;
  4. boolean visit;
  5. StackNode(TreeNode root) {
  6. this.root = root;
  7. }
  8. }
  9. public List<Integer> postorderTraversal(TreeNode root) {
  10. List<Integer> ans = new ArrayList<Integer>();
  11. if(root == null) return ans;
  12. List<StackNode> vector = new ArrayList<StackNode>();
  13. StackNode node;
  14. vector.add(new StackNode(root));
  15. while(vector.size() != 0) {
  16. node = vector.get(vector.size() - 1);
  17. vector.remove(vector.size() - 1);
  18. if(node != null) {
  19. if(!node.visit) {
  20. node.visit = true;
  21. vector.add(node);
  22. if(node.root.right != null) vector.add(new StackNode(node.root.right));
  23. if(node.root.left != null) vector.add(new StackNode(node.root.left));
  24. } else if(node.root != null){
  25. ans.add(node.root.val);
  26. }
  27. }
  28. }
  29. return ans;
  30. }
  31. }

103 Binary Tree Zigzag Level Order Traversal

https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/

题目描述

Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

For example:
Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its zigzag level order traversal as:

[
  [3],
  [20,9],
  [15,7]
]

代码

  1. class Solution {
  2. public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
  3. List<List<Integer>> ans = new ArrayList<>();
  4. robot(root, 0, ans);
  5. for(int i = 0; i < ans.size(); i++) {
  6. if(i % 2 != 0) {
  7. Collections.reverse(ans.get(i));
  8. }
  9. }
  10. return ans;
  11. }
  12. private void robot(TreeNode root, int level, List<List<Integer>> ans) {
  13. if(root == null) return;
  14. if(ans.size() <= level) {
  15. ans.add(new ArrayList());
  16. }
  17. ans.get(level).add(root.val);
  18. robot(root.left, level + 1, ans);
  19. robot(root.right, level + 1, ans);
  20. }
  21. }

105 Construct Binary Tree from Preorder and Inorder Traversal

https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/

题目描述

Given preorder and inorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

代码

  1. class Solution {
  2. public TreeNode buildTree(int[] pre, int[] in) {
  3. return robot(pre, in, 0, 0, in.length - 1);
  4. }
  5. private TreeNode robot(int[] pre, int[] in, int preStart, int inStart, int inEnd) {
  6. if(preStart >= pre.length || inStart > inEnd) return null;
  7. // 找到pos
  8. TreeNode root = new TreeNode(pre[preStart]);
  9. int index = 0;
  10. for(int i = inStart; i <= inEnd; i++) {
  11. if(in[i] == root.val) {
  12. index = i;
  13. break;
  14. }
  15. }
  16. root.left = robot(pre, in, preStart + 1, inStart, index - 1);
  17. root.right = robot(pre, in, preStart + 1 + index - inStart, index + 1, inEnd);
  18. return root;
  19. }
  20. }

106 Construct Binary Tree from Inorder and Postorder Traversal

https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/

题目描述

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

代码

  1. class Solution {
  2. public TreeNode buildTree(int[] in, int[] post) {
  3. return robot(in, post, 0, in.length - 1, 0, post.length - 1);
  4. }
  5. private TreeNode robot(int[] in, int[] post, int inStart, int inEnd, int postStart, int postEnd) {
  6. if(postStart > postEnd) return null;
  7. TreeNode root = new TreeNode(post[postEnd]);
  8. int pos = 0;// 找到pos
  9. for(int i = inStart; i <= inEnd; i++) {
  10. if(in[i] == root.val) {
  11. pos = i;
  12. break;
  13. }
  14. }
  15. root.left = robot(in, post, inStart, pos - 1, postStart, postStart + pos - inStart - 1);
  16. root.right = robot(in, post, pos + 1, inEnd, postEnd + pos - inEnd, postEnd - 1);
  17. return root;
  18. }
  19. }

96 Unique Binary Search Trees

https://leetcode.com/problems/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

代码

  1. public int numTrees(int n) {
  2. int[] ans = new int[n + 2];
  3. ans[0] = 1; ans[1] = 1; ans[2] = 2;
  4. // f(n) = f(0)*f(n-1) + f(1)*f(n-2) + ……
  5. for(int i = 3; i <= n; i++) {
  6. for(int j = 0; j <= i - 1; j++) {
  7. ans[i] += ans[j] * ans[i - j - 1];
  8. }
  9. }
  10. return ans[n];
  11. }

95 Unique Binary Search Trees II

https://leetcode.com/problems/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

代码

  1. class Solution {
  2. public List<TreeNode> generateTrees(int n) {
  3. if(n <= 0) return new ArrayList<>();
  4. return build(1, n);
  5. }
  6. private List<TreeNode> build(int start, int end) {
  7. List<TreeNode> roots = new ArrayList<>();
  8. if(start > end) {
  9. // null也要放入,否则下面的双重循环进不去
  10. roots.add(null);
  11. return roots;
  12. }
  13. if(start == end) {
  14. roots.add(new TreeNode(start));
  15. return roots;
  16. }
  17. for(int i = start; i <= end; i++) {
  18. List<TreeNode> leftList = build(start, i - 1);
  19. List<TreeNode> rightList = build(i + 1, end);
  20. for(TreeNode left : leftList) {
  21. for(TreeNode right : rightList) {
  22. TreeNode root = new TreeNode(i);
  23. root.left = left;
  24. root.right = right;
  25. roots.add(root);
  26. }
  27. }
  28. }
  29. return roots;
  30. }
  31. }

98 Validate Binary Search Tree

https://leetcode.com/problems/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   3

Binary tree [2,1,3], return true.

Example 2:

    1
   / \
  2   3

Binary tree [1,2,3], return false.

代码

  1. public boolean isValidBST(TreeNode root) {
  2. // 用long型
  3. return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
  4. }
  5. private boolean isValidBST(TreeNode root, long min, long max) {
  6. if(root == null) return true;
  7. if(root.val >= max || root.val <= min) return false;
  8. return isValidBST(root.left, min, root.val) && isValidBST(root.right, root.val, max);
  9. }

99 Recover Binary Search Tree

https://leetcode.com/problems/recover-binary-search-tree/

题目描述

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

Recover the tree without changing its structure.

Note:
A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?

代码

  1. class Solution {
  2. TreeNode first = null, second = null;
  3. TreeNode pre = new TreeNode(Integer.MIN_VALUE);
  4. public void recoverTree(TreeNode root) {
  5. if(root == null) return;
  6. robot(root);
  7. if(first != null && second != null) {
  8. int tmp = first.val;
  9. first.val = second.val;
  10. second.val = tmp;
  11. }
  12. }
  13. private void robot(TreeNode root) {
  14. if(root == null) return;
  15. robot(root.left);
  16. // 找到交换的两个节点
  17. if(first == null && pre.val >= root.val) {
  18. first = pre;
  19. }
  20. if(first != null && pre.val >= root.val) {
  21. second = root;
  22. }
  23. pre = root;
  24. robot(root.right);
  25. }
  26. }

450 Delete Node in a BST

https://leetcode.com/problems/delete-node-in-a-bst/

题目描述

Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.

Basically, the deletion can be divided into two stages:

Search for a node to remove.
If the node is found, delete the node.

Note: Time complexity should be O(height of tree).

Example:

root = [5,3,6,2,4,null,7]
key = 3

    5
   / \
  3   6
 / \   \
2   4   7

Given key to delete is 3. So we find the node with value 3 and delete it.

One valid answer is [5,4,6,2,null,null,7], shown in the following BST.

    5
   / \
  4   6
 /     \
2       7

Another valid answer is [5,2,6,null,4,null,7].

    5
   / \
  2   6
   \   \
    4   7

代码

  1. class Solution {
  2. TreeNode target = null;
  3. TreeNode targetParent = null;
  4. public TreeNode deleteNode(TreeNode root, int key) {
  5. // 1. 找到目标节点
  6. find(root, key);
  7. if(target == null) return root;
  8. // 2. update
  9. if(target == root) {
  10. if(target.left == null && target.right == null) return null;
  11. targetParent = target.left == null ? target.right : target.left;
  12. if(target.left != null) {
  13. getMaxNode(targetParent).right = target.right;
  14. } else {
  15. // target.right = null;
  16. }
  17. return targetParent;
  18. }
  19. if(target.left != null) {
  20. getMaxNode(target.left).right = target.right;
  21. adjust(targetParent, target, target.left);
  22. } else if(target.right != null) {
  23. adjust(targetParent, target, target.right);
  24. } else {
  25. adjust(targetParent, target, null);
  26. }
  27. return root;
  28. }
  29. private void adjust(TreeNode targetParent, TreeNode target, TreeNode replace) {
  30. if(targetParent.left == target) targetParent.left = replace;
  31. if(targetParent.right == target) targetParent.right = replace;
  32. }
  33. private TreeNode getMaxNode(TreeNode root) {
  34. if(root == null) return null;
  35. while(root.right != null) {
  36. root = root.right;
  37. }
  38. return root;
  39. }
  40. private void find(TreeNode root, int key) {
  41. if(root == null) return;
  42. if(root.left != null && root.left.val == key) {
  43. targetParent = root;
  44. }
  45. if(root.right != null && root.right.val == key) {
  46. targetParent = root;
  47. }
  48. if(root.val == key) {
  49. target = root;
  50. return;
  51. }
  52. find(root.left, key);
  53. find(root.right, key);
  54. }
  55. }

230 Kth Smallest Element in a BST

https://leetcode.com/problems/kth-smallest-element-in-a-bst/

题目描述

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

Note:
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.

Follow up:
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?

Credits:Special thanks to @ts for adding this problem and creating all test cases.

代码

  1. class Solution {
  2. int ans = 0;
  3. int count = 0;
  4. public int kthSmallest(TreeNode root, int k) {
  5. count = k;
  6. robot(root);
  7. return ans;
  8. }
  9. private void robot(TreeNode root) {
  10. if(root == null) return;
  11. robot(root.left);
  12. if(--count == 0) {
  13. ans = root.val;
  14. return;
  15. }
  16. robot(root.right);
  17. }
  18. }

100 Same Tree

https://leetcode.com/problems/same-tree/

题目描述

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

代码

  1. class Solution {
  2. public boolean isSameTree(TreeNode p, TreeNode q) {
  3. if(p == null && q == null) return true;
  4. if(p == null || q == null) return false;
  5. if(p.val != q.val) return false;
  6. return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
  7. }
  8. }

101 Symmetric Tree

https://leetcode.com/problems/symmetric-tree/

题目描述

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3

Note:
Bonus points if you could solve it both recursively and iteratively.

代码

  1. class Solution {
  2. public boolean isSymmetric(TreeNode root) {
  3. if(root == null) return true;
  4. return isSymmetric(root.left, root.right);
  5. }
  6. private boolean isSymmetric(TreeNode p, TreeNode q) {
  7. if(p == null && q == null) return true;
  8. if(p == null || q == null) return false;
  9. if(p.val != q.val) return false;
  10. return isSymmetric(p.left, q.right) && isSymmetric(p.right, q.left);
  11. }
  12. }

102 Binary Tree Level Order Traversal

https://leetcode.com/problems/binary-tree-level-order-traversal/

题目描述

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:
Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]

代码

  1. class Solution {
  2. public List<List<Integer>> levelOrder(TreeNode root) {
  3. List<List<Integer>> ans = new ArrayList<>();
  4. robot(root, 0, ans);
  5. return ans;
  6. }
  7. private void robot(TreeNode root, int level, List<List<Integer>> ans) {
  8. if(root == null) return;
  9. if(ans.size() <= level) {
  10. ans.add(new ArrayList());
  11. }
  12. ans.get(level).add(root.val);
  13. robot(root.left, level + 1, ans);
  14. robot(root.right, level + 1, ans);
  15. }
  16. }

107 Binary Tree Level Order Traversal II

https://leetcode.com/problems/binary-tree-level-order-traversal-ii/

题目描述

Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

For example:
Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its bottom-up level order traversal as:

[
  [15,7],
  [9,20],
  [3]
]

代码

  1. class Solution {
  2. public List<List<Integer>> levelOrderBottom(TreeNode root) {
  3. List<List<Integer>> ans = new ArrayList<>();
  4. robot(root, 0, ans);
  5. Collections.reverse(ans);
  6. return ans;
  7. }
  8. private void robot(TreeNode root, int level, List<List<Integer>> ans) {
  9. if(root == null) return;
  10. if(ans.size() <= level) {
  11. ans.add(new ArrayList());
  12. }
  13. ans.get(level).add(root.val);
  14. robot(root.left, level + 1, ans);
  15. robot(root.right, level + 1, ans);
  16. }
  17. }

104 Maximum Depth of Binary Tree

https://leetcode.com/problems/maximum-depth-of-binary-tree/

题目描述

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

代码

  1. class Solution {
  2. public int maxDepth(TreeNode root) {
  3. if(root == null) return 0;
  4. int left = maxDepth(root.left);
  5. int right = maxDepth(root.right);
  6. return (left == 0 || right == 0) ? (left + right + 1) : Math.max(left, right) + 1;
  7. }
  8. }

108 Convert Sorted Array to Binary Search Tree

https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/

题目描述

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example:

Given the sorted array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5

代码

  1. class Solution {
  2. public TreeNode sortedArrayToBST(int[] nums) {
  3. if(nums == null || nums.length == 0) return null;
  4. return robot(nums, 0, nums.length - 1);
  5. }
  6. private TreeNode robot(int[] nums, int start, int end) {
  7. if(start > end) return null;
  8. int mid = start + (end - start) / 2;
  9. TreeNode root = new TreeNode(nums[mid]);
  10. root.left = robot(nums, start, mid - 1);
  11. root.right = robot(nums, mid + 1, end);
  12. return root;
  13. }
  14. }

110 Balanced Binary Tree

https://leetcode.com/problems/balanced-binary-tree/

题目描述

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

代码

  1. class Solution {
  2. public boolean isBalanced(TreeNode root) {
  3. if(root == null) return true;
  4. int left = depth(root.left);
  5. int right = depth(root.right);
  6. return Math.abs(left - right) <= 1 && isBalanced(root.left) && isBalanced(root.right);
  7. }
  8. private int depth(TreeNode root) {
  9. if(root == null) return 0;
  10. return Math.max(depth(root.left), depth(root.right)) + 1;
  11. }
  12. }

173 Binary Search Tree Iterator

https://leetcode.com/problems/binary-search-tree-iterator/

题目描述

Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.

Calling next() will return the next smallest number in the BST.

Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.

Credits:Special thanks to @ts for adding this problem and creating all test cases.

代码

  1. public class BSTIterator {
  2. List<TreeNode> vector = new ArrayList<TreeNode>();
  3. TreeNode curr = null;
  4. public BSTIterator(TreeNode root) {
  5. curr = root;
  6. // 一直放入左儿子(左)
  7. while(curr != null) {
  8. vector.add(curr);
  9. curr = curr.left;
  10. }
  11. }
  12. /** @return whether we have a next smallest number */
  13. public boolean hasNext() {
  14. return vector.size() != 0 || curr != null;
  15. }
  16. /** @return the next smallest number */
  17. public int next() {
  18. // 一直放入左儿子(左)
  19. while(curr != null) {
  20. vector.add(curr);
  21. curr = curr.left;
  22. }
  23. int ans = 0;
  24. // 访问当前元素(中),把右儿子入栈(右)
  25. if(vector.size() != 0) {
  26. curr = vector.get(vector.size() - 1);
  27. vector.remove(vector.size() - 1);
  28. ans = curr.val;
  29. curr = curr.right;
  30. }
  31. return ans;
  32. }
  33. }
  34. /**
  35. * Your BSTIterator will be called like this:
  36. * BSTIterator i = new BSTIterator(root);
  37. * while (i.hasNext()) v[f()] = i.next();
  38. */

111 Minimum Depth of Binary Tree

https://leetcode.com/problems/minimum-depth-of-binary-tree/

题目描述

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

代码

  1. class Solution {
  2. public int minDepth(TreeNode root) {
  3. if(root == null) return 0;
  4. int left = minDepth(root.left);
  5. int right = minDepth(root.right);
  6. return (left == 0 || right == 0) ? (left + right + 1) : Math.min(left, right) + 1;
  7. }
  8. }

112 Path Sum

https://leetcode.com/problems/path-sum/

题目描述

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

For example:
Given the below binary tree and sum = 22,

          5
         / \
        4   8
       /   / \
      11  13  4
     /  \      \
    7    2      1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

代码

  1. class Solution {
  2. public boolean hasPathSum(TreeNode root, int sum) {
  3. if(root == null) return false;
  4. if(root.left == null && root.right == null && sum - root.val == 0) return true;
  5. return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
  6. }
  7. }

113 Path Sum II

https://leetcode.com/problems/path-sum-ii/

题目描述

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

For example:
Given the below binary tree and sum = 22,

          5
         / \
        4   8
       /   / \
      11  13  4
     /  \    / \
    7    2  5   1

return

[
   [5,4,11,2],
   [5,8,4,5]
]

代码

  1. class Solution {
  2. public List<List<Integer>> pathSum(TreeNode root, int sum) {
  3. List<List<Integer>> ans = new ArrayList<>();
  4. robot(root, sum, ans, new ArrayList<>());
  5. return ans;
  6. }
  7. private void robot(TreeNode root, int sum, List<List<Integer>> ans, List<Integer> tmp) {
  8. if(root == null) return;
  9. tmp.add(root.val);
  10. if(root.left == null && root.right == null && sum == root.val) {
  11. ans.add(new ArrayList(tmp));
  12. tmp.remove(tmp.size() - 1);
  13. return;
  14. }
  15. robot(root.left, sum - root.val, ans, tmp);
  16. robot(root.right, sum - root.val, ans, tmp);
  17. tmp.remove(tmp.size() - 1);
  18. }
  19. }

437 Path Sum III

https://leetcode.com/problems/path-sum-iii/

题目描述

You are given a binary tree in which each node contains an integer value.

Find the number of paths that sum to a given value.

The path does not need to start or end at the root or a leaf, but it must go downwards
(traveling only from parent nodes to child nodes).

The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.

Example:

root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8

      10
     /  \
    5   -3
   / \    \
  3   2   11
 / \   \
3  -2   1

Return 3. The paths that sum to 8 are:

1.  5 -> 3
2.  5 -> 2 -> 1
3. -3 -> 11

代码

  1. class Solution {
  2. int ans = 0;
  3. public int pathSum(TreeNode root, int sum) {
  4. // 以每个节点开始做算法
  5. robot(root, sum);
  6. return ans;
  7. }
  8. private void robot(TreeNode root, int sum) {
  9. if(root == null) return;
  10. robot(root.left, sum);
  11. // core,以 root 为起点,遍历所有节点求和
  12. countPath(root, sum);
  13. robot(root.right, sum);
  14. }
  15. private void countPath(TreeNode root, int left) {
  16. if(root == null) return;
  17. left -= root.val;
  18. if(left == 0) ans++;
  19. countPath(root.left, left);
  20. countPath(root.right, left);
  21. }
  22. }

114 Flatten Binary Tree to Linked List

https://leetcode.com/problems/flatten-binary-tree-to-linked-list/

题目描述

Given a binary tree, flatten it to a linked list in-place.

For example,
Given

     1
    / \
   2   5
  / \   \
 3   4   6

The flattened tree should look like:

   1
    \
     2
      \
       3
        \
         4
          \
           5
            \
             6

click to show hints.

Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.

代码

  1. public class Solution {
  2. public void flatten(TreeNode root) {
  3. if(root == null) return;
  4. flatten(root.left);
  5. flatten(root.right);
  6. TreeNode tmp = root.right;
  7. root.right = root.left;
  8. root.left = null;
  9. // root.right 已经是原来的 root.left
  10. while(root.right != null) root = root.right;
  11. root.right = tmp;
  12. }
  13. }

116 Populating Next Right Pointers in Each Node

https://leetcode.com/problems/populating-next-right-pointers-in-each-node/

题目描述

Given a binary tree

struct TreeLinkNode {
  TreeLinkNode *left;
  TreeLinkNode *right;
  TreeLinkNode *next;
}

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

Initially, all next pointers are set to NULL.

Note:

You may only use constant extra space.
You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).

For example,
Given the following perfect binary tree,

     1
   /  \
  2    3
 / \  / \
4  5  6  7

After calling your function, the tree should look like:

     1 -> NULL
   /  \
  2 -> 3 -> NULL
 / \  / \
4->5->6->7 -> NULL

代码

  1. public class Solution {
  2. public void connect(TreeLinkNode root) {
  3. if(root == null) return;
  4. if(root.left != null) {
  5. root.left.next = root.right;
  6. if(root.next != null) {
  7. root.right.next = root.next.left;
  8. }
  9. }
  10. connect(root.left);
  11. connect(root.right);
  12. }
  13. }

117 Populating Next Right Pointers in Each Node II

https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/

题目描述

Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?

Note:
You may only use constant extra space.

For example,
Given the following binary tree,

     1
   /  \
  2    3
 / \    \
4   5    7

After calling your function, the tree should look like:

     1 -> NULL
   /  \
  2 -> 3 -> NULL
 / \    \
4-> 5 -> 7 -> NULL

代码

  1. public class Solution {
  2. public void connect(TreeLinkNode root) {
  3. if(root == null) return;
  4. if(root.left == null && root.right == null) return;
  5. TreeLinkNode p = root.next;
  6. while(p != null) {
  7. if(p.left != null) {
  8. p = p.left;
  9. break;
  10. }
  11. if(p.right != null) {
  12. p = p.right;
  13. break;
  14. }
  15. p = p.next;
  16. }
  17. if(root.right != null) root.right.next = p;
  18. if(root.left != null) root.left.next = root.right == null ? p : root.right;
  19. // 先右子树,因为 next 节点依赖右边
  20. connect(root.right);
  21. connect(root.left);
  22. }
  23. }

124 Binary Tree Maximum Path Sum

https://leetcode.com/problems/binary-tree-maximum-path-sum/

题目描述

Given a binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.

For example:
Given the below binary tree,

   1
  / \
 2   3

Return 6.

代码

  1. class Solution {
  2. int max = Integer.MIN_VALUE;
  3. public int maxPathSum(TreeNode root) {
  4. robot(root);
  5. return max;
  6. }
  7. private int robot(TreeNode root) {
  8. if(root == null) return 0;
  9. int left = robot(root.left);
  10. int right = robot(root.right);
  11. int ans = root.val;
  12. if(Math.max(left, right) > 0) {
  13. ans += Math.max(left, right);
  14. }
  15. max = Math.max(max, root.val);
  16. max = Math.max(max, left + root.val);
  17. max = Math.max(max, right + root.val);
  18. max = Math.max(max, left + right + root.val);
  19. return ans;
  20. }
  21. }

129 Sum Root to Leaf Numbers

https://leetcode.com/problems/sum-root-to-leaf-numbers/

题目描述

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.

Find the total sum of all root-to-leaf numbers.

For example,

    1
   / \
  2   3

The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.

Return the sum = 12 + 13 = 25.

代码

  1. class Solution {
  2. public int sumNumbers(TreeNode root) {
  3. return robot(root, 0);
  4. }
  5. private int robot(TreeNode root, int sum) {
  6. if(root == null) return 0;
  7. sum = sum * 10 + root.val;
  8. if(root.left == null && root.right == null) return sum;
  9. return robot(root.left, sum) + robot(root.right, sum);
  10. }
  11. }

404 Sum of Left Leaves

https://leetcode.com/problems/sum-of-left-leaves/

题目描述

Find the sum of all left leaves in a given binary tree.

Example:

    3
   / \
  9  20
    /  \
   15   7

There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

代码

  1. class Solution {
  2. int ans = 0;
  3. public int sumOfLeftLeaves(TreeNode root) {
  4. robot(root, false);
  5. return ans;
  6. }
  7. private void robot(TreeNode root, boolean isLeft) {
  8. if(root == null) return;
  9. if(root.left == null && root.right == null && isLeft) {
  10. ans += root.val;
  11. return;
  12. }
  13. robot(root.left, true);
  14. robot(root.right, false);
  15. }
  16. }

199 Binary Tree Right Side View

https://leetcode.com/problems/binary-tree-right-side-view/

题目描述

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

For example:
Given the following binary tree,

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---

You should return [1, 3, 4].

Credits:Special thanks to @amrsaqr for adding this problem and creating all test cases.

代码

  1. class Solution {
  2. public List<Integer> rightSideView(TreeNode root) {
  3. List<Integer> ans = new ArrayList<>();
  4. robot(root, ans, 0);
  5. return ans;
  6. }
  7. private void robot(TreeNode root, List<Integer> ans, int height) {
  8. if(root == null) return;
  9. if(ans.size() <= height) {
  10. ans.add(root.val);
  11. }
  12. ans.set(height, root.val);
  13. robot(root.left, ans, height + 1);
  14. robot(root.right, ans, height + 1);
  15. }
  16. }

222 Count Complete Tree Nodes

https://leetcode.com/problems/count-complete-tree-nodes/

题目描述

Given a complete binary tree, count the number of nodes.

Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

代码

  1. class Solution {
  2. public int countNodes(TreeNode root) {
  3. if(root == null) return 0;
  4. int left = leftHeight(root);
  5. int right = rightHeight(root);
  6. if(left == right) return (1 << left) - 1;
  7. return countNodes(root.left) + countNodes(root.right) + 1;
  8. }
  9. private int leftHeight(TreeNode root) {
  10. int depth = 0;
  11. while(root != null) {
  12. depth++;
  13. root = root.left;
  14. }
  15. return depth;
  16. }
  17. private int rightHeight(TreeNode root) {
  18. int depth = 0;
  19. while(root != null) {
  20. depth++;
  21. root = root.right;
  22. }
  23. return depth;
  24. }
  25. }

226 Invert Binary Tree

https://leetcode.com/problems/invert-binary-tree/

题目描述

Invert a binary tree.

     4
   /   \
  2     7
 / \   / \
1   3 6   9

to

     4
   /   \
  7     2
 / \   / \
9   6 3   1

Trivia:
This problem was inspired by this original tweet by Max Howell:
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.

代码

  1. public class Solution {
  2. public TreeNode invertTree(TreeNode root) {
  3. if(root == null) return root;
  4. TreeNode tmp = root.left;
  5. root.left = root.right;
  6. root.right = tmp;
  7. invertTree(root.left);
  8. invertTree(root.right);
  9. return root;
  10. }
  11. }

235 Lowest Common Ancestor of a Binary Search Tree

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/

题目描述

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

        _______6______
       /              \
    ___2__          ___8__
   /      \        /      \
   0      _4       7       9
         /  \
         3   5

For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

代码

  1. class Solution {
  2. TreeNode ans = null;
  3. public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
  4. if(root == null || p == null || q == null) return null;
  5. int min = Math.min(p.val, q.val);
  6. int max = Math.max(p.val, q.val);
  7. robot(root, min, max);
  8. return ans;
  9. }
  10. private void robot(TreeNode root, int min, int max) {
  11. if(root == null) return;
  12. robot(root.left, min, max);
  13. if(root.val <= max && root.val >= min) {
  14. ans = root;
  15. return;
  16. }
  17. robot(root.right, min, max);
  18. }
  19. }

236 Lowest Common Ancestor of a Binary Tree

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/

题目描述

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

        _______3______
       /              \
    ___5__          ___1__
   /      \        /      \
   6      _2       0       8
         /  \
         7   4

For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

代码

  1. public class Solution {
  2. public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
  3. if(root == null || root == p || root == q) {
  4. return root;
  5. }
  6. TreeNode left = lowestCommonAncestor(root.left, p, q);
  7. TreeNode right = lowestCommonAncestor(root.right, p, q);
  8. if(left != null && right != null) return root;
  9. return left == null ? right : left;
  10. }
  11. }

257 Binary Tree Paths

https://leetcode.com/problems/binary-tree-paths/

题目描述

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

   1
 /   \
2     3
 \
  5

All root-to-leaf paths are:

["1->2->5", "1->3"]

Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

代码

  1. class Solution {
  2. public List<String> binaryTreePaths(TreeNode root) {
  3. List<String> ans = new ArrayList<>();
  4. robot(root, ans, "");
  5. return ans;
  6. }
  7. private void robot(TreeNode root, List<String> ans, String path) {
  8. if(root == null) return;
  9. if(root.left == null && root.right == null) {
  10. ans.add(path + root.val);
  11. return;
  12. }
  13. robot(root.left, ans, path + root.val + "->");
  14. robot(root.right, ans, path + root.val + "->");
  15. }
  16. }

297 Serialize and Deserialize Binary Tree

https://leetcode.com/problems/serialize-and-deserialize-binary-tree/

题目描述

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

For example, you may serialize the following tree

    1
   / \
  2   3
     / \
    4   5

as "[1,2,3,null,null,4,5]", just the same as how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.

Credits:Special thanks to @Louis1992 for adding this problem and creating all test cases.

代码

  1. public class Codec {
  2. private static final String NULL = "*";
  3. private static final String SEP = ",";
  4. // Encodes a tree to a single string.
  5. public String serialize(TreeNode root) {
  6. StringBuilder ans = new StringBuilder();
  7. Queue<TreeNode> queue = new LinkedList<>();
  8. queue.add(root);
  9. while(!queue.isEmpty()) {
  10. TreeNode node = queue.poll();
  11. if(node == null) {
  12. ans.append(NULL);
  13. } else {
  14. ans.append(node.val);
  15. queue.add(node.left);
  16. queue.add(node.right);
  17. }
  18. ans.append(SEP);
  19. }
  20. return ans.substring(0, ans.length() - 1).toString();
  21. }
  22. // Decodes your encoded data to tree.
  23. public TreeNode deserialize(String data) {
  24. if(data == null) return null;
  25. String[] vals = data.split(",");
  26. if(vals.length == 0 || NULL.equals(vals[0])) return null;
  27. Queue<TreeNode> queue = new LinkedList<>();
  28. TreeNode root = buildNode(vals[0]);
  29. queue.add(root);
  30. TreeNode node = null;
  31. for(int i = 1; i < vals.length; i += 2) {
  32. while((node = queue.poll()) == null);
  33. node.left = buildNode(vals[i]);
  34. node.right = buildNode(i + 1 < vals.length ? vals[i + 1] : NULL);
  35. queue.add(node.left);
  36. queue.add(node.right);
  37. }
  38. return root;
  39. }
  40. private TreeNode buildNode(String val) {
  41. if(val == null || val.equals(NULL)) return null;
  42. return new TreeNode(Integer.valueOf(val));
  43. }
  44. }
  45. // Your Codec object will be instantiated and called as such:
  46. // Codec codec = new Codec();
  47. // codec.deserialize(codec.serialize(root));

递归

  1. public class Codec {
  2. // Encodes a tree to a single string.
  3. public String serialize(TreeNode root) {
  4. StringBuilder sb = new StringBuilder();
  5. robot(root, sb);
  6. return sb.toString();
  7. }
  8. public void robot(TreeNode root, StringBuilder sb) {
  9. if(root == null) {
  10. sb.append("X").append(",");
  11. } else {
  12. sb.append(root.val + "").append(",");
  13. robot(root.left, sb);
  14. robot(root.right, sb);
  15. }
  16. }
  17. // Decodes your encoded data to tree.
  18. public TreeNode deserialize(String data) {
  19. Deque<String> nodes = new LinkedList<>();
  20. nodes.addAll(Arrays.asList(data.split(",")));
  21. return buildTree(nodes);
  22. }
  23. public TreeNode buildTree(Deque<String> nodes) {
  24. String val = nodes.remove();
  25. if(val.equals("X")) {
  26. return null;
  27. } else {
  28. TreeNode root = new TreeNode(Integer.valueOf(val));
  29. root.left = buildTree(nodes);
  30. root.right = buildTree(nodes);
  31. return root;
  32. }
  33. }
  34. }
  35. // Your Codec object will be instantiated and called as such:
  36. // Codec codec = new Codec();
  37. // codec.deserialize(codec.serialize(root));

449 Serialize and Deserialize BST

https://leetcode.com/problems/serialize-and-deserialize-bst/

题目描述

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary search tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary search tree can be serialized to a string and this string can be deserialized to the original tree structure.

The encoded string should be as compact as possible.

Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.

代码

  1. public class Codec {
  2. // Encodes a tree to a single string.
  3. public String serialize(TreeNode root) {
  4. List<Integer> preList = new ArrayList<>();
  5. robot(root, preList);
  6. return preList.toString().substring(1, preList.toString().length() - 1);
  7. }
  8. private void robot(TreeNode root, List<Integer> list) {
  9. if(root == null) return;
  10. list.add(root.val);
  11. robot(root.left, list);
  12. robot(root.right, list);
  13. }
  14. // Decodes your encoded data to tree.
  15. public TreeNode deserialize(String data) {
  16. if(data == null || data.trim().equals("")) return null;
  17. int[] pre = parse(data);
  18. int[] in = pre.clone();
  19. Arrays.sort(in);
  20. return buildTree(pre, in);
  21. }
  22. private int[] parse(String data) {
  23. int[] array = new int[data.split(",").length];
  24. int i = 0;
  25. for(String val : data.split(",")) {
  26. array[i++] = Integer.valueOf(val.trim());
  27. }
  28. return array;
  29. }
  30. private TreeNode build(int preStart, int inStart, int inEnd, int[] pre, int[] in) {
  31. if(preStart >= pre.length || inStart > inEnd) {
  32. return null;
  33. }
  34. TreeNode root = new TreeNode(pre[preStart]);
  35. int inIndex = 0;
  36. for(int i = inStart; i <= inEnd; i++) {
  37. if(in[i] == root.val) {
  38. inIndex = i;
  39. break;
  40. }
  41. }
  42. root.left = build(preStart + 1, inStart, inIndex - 1, pre, in);
  43. root.right = build(preStart + inIndex - inStart + 1, inIndex + 1, inEnd, pre, in);
  44. return root;
  45. }
  46. private TreeNode buildTree(int[] preorder, int[] inorder) {
  47. return build(0, 0, inorder.length - 1, preorder, inorder);
  48. }
  49. }
  50. // Your Codec object will be instantiated and called as such:
  51. // Codec codec = new Codec();
  52. // codec.deserialize(codec.serialize(root));

337 House Robber III

https://leetcode.com/problems/house-robber-iii/

题目描述

The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automatically contact the police if two directly-linked houses were broken into on the same night.

Determine the maximum amount of money the thief can rob tonight without alerting the police.

Example 1:

     3
    / \
   2   3
    \   \ 
     3   1

Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.

Example 2:

     3
    / \
   4   5
  / \   \ 
 1   3   1

Maximum amount of money the thief can rob = 4 + 5 = 9.

Credits:Special thanks to @dietpepsi for adding this problem and creating all test cases.

代码

  1. class Solution {
  2. public int rob(TreeNode root) {
  3. if(root == null) return 0;
  4. return Math.max(robIn(root), robEx(root));
  5. }
  6. private int robIn(TreeNode root) {
  7. if(root == null) return 0;
  8. return root.val + robEx(root.left) + robEx(root.right);
  9. }
  10. private int robEx(TreeNode root) {
  11. if(root == null) return 0;
  12. // 可以不抢下一个节点
  13. return rob(root.left) + rob(root.right);
  14. }
  15. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注