[关闭]
@Yano 2015-12-30T03:27:46.000000Z 字数 18923 阅读 9312

LeetCode之Depth-first Search题目汇总

LeetCode

我的博客:http://blog.csdn.net/yano_nankai
LeetCode题解:https://github.com/LjyYano/LeetCode


LeetCode 题目汇总

LeetCode之Array题目汇总
LeetCode之Hash Table题目汇总
LeetCode之Linked List题目汇总
LeetCode之Math题目汇总
LeetCode之String题目汇总
LeetCode之Binary Search题目汇总
LeetCode之Divide and Conquer题目汇总
LeetCode之Dynamic Programming题目汇总
LeetCode之Backtracing题目汇总
LeetCode之Stack题目汇总
LeetCode之Sort题目汇总
LeetCode之Bit Manipulation题目汇总
LeetCode之Tree题目汇总
LeetCode之Depth-first Search题目汇总
LeetCode之Breadth-first Search题目汇总
LeetCode之Graph题目汇总
LeetCode之Trie题目汇总
LeetCode之Design题目汇总


文章目录:


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

核心代码:

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

Binary Tree Paths

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

For example, given the following binary tree:

  1. 1
  2. / \
  3. 2 3
  4. \
  5. 5

All root-to-leaf paths are:

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

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


  1. List<String> rt = new ArrayList<String>();
  2. List<Integer> path = new ArrayList<Integer>();
  3. public List<String> binaryTreePaths(TreeNode root) {
  4. findPath(root);
  5. return rt;
  6. }
  7. void findPath(TreeNode root) {
  8. if (root == null) {
  9. return;
  10. }
  11. path.add(root.val);
  12. // 是一条路径,将path添加到rt中
  13. if (root.left == null && root.right == null) {
  14. StringBuffer sb = new StringBuffer();
  15. sb.append(path.get(0));
  16. for (int i = 1; i < path.size(); i++) {
  17. sb.append("->" + path.get(i));
  18. }
  19. rt.add(sb.toString());
  20. }
  21. findPath(root.left);
  22. findPath(root.right);
  23. path.remove(path.size() - 1);
  24. }

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. 1 <---
  2. / \
  3. 2 3 <---
  4. \ \
  5. 5 4 <---

You should return [1, 3, 4].

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


1. 递归求解

二叉树,从右边向左边看。那么除了最右边的一个list1,还会有一个相对于最右边的list稍微靠左边一点的list2,如果list2比list1长,则list2较长的部分也是结果。

举个例子:

  1. 1 <---
  2. / \
  3. 2 3 <---
  4. \ \
  5. 5 4 <---
  6. \
  7. 6 <---

list1是[1, 3, 4], list2是[1, 2, 5, 6]。list2比list1长,长出的部分是6,也在结果之中。

  1. public List<Integer> rightSideView(TreeNode root) {
  2. List<Integer> rt = new ArrayList<Integer>();
  3. if (root == null) {
  4. return rt;
  5. }
  6. rt.add(root.val);
  7. List<Integer> left = rightSideView(root.left);
  8. List<Integer> right = rightSideView(root.right);
  9. rt.addAll(right);
  10. if (left.size() > right.size()) {
  11. rt.addAll(left.subList(right.size(), left.size()));
  12. }
  13. return rt;
  14. }

2. 插入特殊结点

通过插入特殊结点,来判断一层是否结束。这样做的好处是不用统计每一层结点数目。

  1. public List<Integer> rightSideView2(TreeNode root) {
  2. List<Integer> rt = new ArrayList<Integer>();
  3. if (root == null) {
  4. return rt;
  5. }
  6. final TreeNode END = new TreeNode(0);
  7. Deque<TreeNode> deque = new LinkedList<TreeNode>();
  8. deque.add(root);
  9. deque.add(END);
  10. while (!deque.isEmpty()) {
  11. TreeNode p = deque.pop();
  12. if (p == END) {
  13. if (!deque.isEmpty()) {
  14. deque.add(END);
  15. }
  16. } else {
  17. // 如果deque的下一个是END,则p是层序的最后一个,加入结果rt
  18. if (deque.peek() == END) {
  19. rt.add(p.val);
  20. }
  21. if (p.left != null) {
  22. deque.add(p.left);
  23. }
  24. if (p.right != null) {
  25. deque.add(p.right);
  26. }
  27. }
  28. }
  29. return rt;
  30. }

3. 计数法

定义两个变量,toBePrinted和nextLevel。

toBePrinted:当前待打印结点的数量  
nextLevel:下一层的结点数量

通过Deque来进行统计。

  1. public List<Integer> rightSideView3(TreeNode root) {
  2. List<Integer> rt = new ArrayList<Integer>();
  3. if (root == null) {
  4. return rt;
  5. }
  6. Deque<TreeNode> deque = new LinkedList<TreeNode>();
  7. deque.add(root);
  8. int toBePrinted = 1;
  9. int nextLevel = 0;
  10. List<Integer> level = new LinkedList<Integer>();
  11. while (!deque.isEmpty()) {
  12. TreeNode p = deque.poll();
  13. level.add(p.val);
  14. toBePrinted--;
  15. if (p.left != null) {
  16. deque.addLast(p.left);
  17. nextLevel++;
  18. }
  19. if (p.right != null) {
  20. deque.addLast(p.right);
  21. nextLevel++;
  22. }
  23. if (toBePrinted == 0) {
  24. toBePrinted = nextLevel;
  25. nextLevel = 0;
  26. rt.add(p.val);
  27. level.clear();
  28. }
  29. }
  30. return rt;
  31. }

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. int p;
  2. int[] postorder;
  3. int[] inorder;
  4. public TreeNode buildTree(int[] inorder, int[] postorder) {
  5. this.p = postorder.length - 1;
  6. this.inorder = inorder;
  7. this.postorder = postorder;
  8. return buildTree(0, postorder.length);
  9. }
  10. TreeNode buildTree(int start, int end) {
  11. if (start >= end) {
  12. return null;
  13. }
  14. TreeNode root = new TreeNode(postorder[p]);
  15. int i;
  16. for (i = start; i < end && postorder[p] != inorder[i]; i++)
  17. ;
  18. p--;
  19. root.right = buildTree(i + 1, end);
  20. root.left = buildTree(start, i);
  21. return root;
  22. }

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. int p = 0;
  2. int[] preorder;
  3. int[] inorder;
  4. public TreeNode buildTree(int[] preorder, int[] inorder) {
  5. this.preorder = preorder;
  6. this.inorder = inorder;
  7. return buildTree(0, preorder.length);
  8. }
  9. TreeNode buildTree(int start, int end) {
  10. if (start >= end) {
  11. return null;
  12. }
  13. TreeNode root = new TreeNode(preorder[p]);
  14. int i;
  15. for (i = start; i < end && preorder[p] != inorder[i]; i++)
  16. ;
  17. p++;
  18. root.left = buildTree(start, i);
  19. root.right = buildTree(i + 1, end);
  20. return root;
  21. }

Convert Sorted Array to Binary Search Tree

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


  1. int[] nums;
  2. public TreeNode sortedArrayToBST(int[] nums) {
  3. this.nums = nums;
  4. return buildBST(0, nums.length);
  5. }
  6. TreeNode buildBST(int start, int end) {
  7. if (start >= end) {
  8. return null;
  9. }
  10. int mid = (start + end) / 2;
  11. TreeNode root = new TreeNode(nums[mid]);
  12. root.left = buildBST(start, mid);
  13. root.right = buildBST(mid + 1, end);
  14. return root;
  15. }
  16. public TreeNode sortedArrayToBST2(int[] nums) {
  17. if (nums.length == 0) {
  18. return null;
  19. }
  20. if (nums.length == 1) {
  21. return new TreeNode(nums[0]);
  22. }
  23. int mid = nums.length / 2;
  24. TreeNode root = new TreeNode(nums[mid]);
  25. root.left = sortedArrayToBST2(Arrays.copyOfRange(nums, 0, mid));
  26. root.right = sortedArrayToBST2(Arrays.copyOfRange(nums, mid + 1,
  27. nums.length));
  28. return root;
  29. }

Convert Sorted List to Binary Search Tree

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.


  1. ListNode cutAtMid(ListNode head) {
  2. if (head == null) {
  3. return null;
  4. }
  5. ListNode fast = head;
  6. ListNode slow = head;
  7. ListNode pslow = head;
  8. while (fast != null && fast.next != null) {
  9. pslow = slow;
  10. slow = slow.next;
  11. fast = fast.next.next;
  12. }
  13. pslow.next = null;
  14. return slow;
  15. }
  16. public TreeNode sortedListToBST(ListNode head) {
  17. if (head == null) {
  18. return null;
  19. }
  20. if (head.next == null) {
  21. return new TreeNode(head.val);
  22. }
  23. ListNode mid = cutAtMid(head);
  24. TreeNode root = new TreeNode(mid.val);
  25. root.left = sortedListToBST(head);
  26. root.right = sortedListToBST(mid.next);
  27. return root;
  28. }

Course Schedule

There are a total of n courses you have to take, labeled from 0 to n - 1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?

For example:

  1. 2, [[1,0]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.

  1. 2, [[1,0],[0,1]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.

Note:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.


题目等价为:检测图中是否有环

参考网址:LeetCode – Course Schedule (Java)

BFS:

  1. // BFS
  2. public static boolean canFinish(int numCourses, int[][] prerequisites) {
  3. // 参数检查
  4. if (prerequisites == null) {
  5. return false;
  6. }
  7. int len = prerequisites.length;
  8. if (numCourses <= 0 || len == 0) {
  9. return true;
  10. }
  11. // 记录每个course的prerequisites的数量
  12. int[] pCounter = new int[numCourses];
  13. for (int i = 0; i < len; i++) {
  14. pCounter[prerequisites[i][0]]++;
  15. }
  16. // 用队列记录可以直接访问的course
  17. LinkedList<Integer> queue = new LinkedList<Integer>();
  18. for (int i = 0; i < numCourses; i++) {
  19. if (pCounter[i] == 0) {
  20. queue.add(i);
  21. }
  22. }
  23. // 取出队列的course,判断
  24. int numNoPre = queue.size();
  25. while (!queue.isEmpty()) {
  26. int top = queue.remove();
  27. for (int i = 0; i < len; i++) {
  28. // 该course是某个course的prerequisites
  29. if (prerequisites[i][1] == top) {
  30. pCounter[prerequisites[i][0]]--;
  31. if (pCounter[prerequisites[i][0]] == 0) {
  32. numNoPre++;
  33. queue.add(prerequisites[i][0]);
  34. }
  35. }
  36. }
  37. }
  38. return numNoPre == numCourses;
  39. }

DFS:

  1. // DFS
  2. public static boolean canFinish2(int numCourses, int[][] prerequisites) {
  3. // 参数检查
  4. if (prerequisites == null) {
  5. return false;
  6. }
  7. int len = prerequisites.length;
  8. if (numCourses <= 0 || len == 0) {
  9. return true;
  10. }
  11. int[] visit = new int[numCourses];
  12. // key:course;value:以该course为prerequisites的course
  13. HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>();
  14. // 初始化map
  15. for (int[] p : prerequisites) {
  16. if (map.containsKey(p[1])) {
  17. map.get(p[1]).add(p[0]);
  18. } else {
  19. ArrayList<Integer> l = new ArrayList<Integer>();
  20. l.add(p[0]);
  21. map.put(p[1], l);
  22. }
  23. }
  24. // dfs
  25. for (int i = 0; i < numCourses; i++) {
  26. if (!canFinishDFS(map, visit, i)) {
  27. return false;
  28. }
  29. }
  30. return true;
  31. }
  32. private static boolean canFinishDFS(
  33. HashMap<Integer, ArrayList<Integer>> map, int[] visit, int i) {
  34. if (visit[i] == -1) {
  35. return false;
  36. }
  37. if (visit[i] == 1) {
  38. return true;
  39. }
  40. visit[i] = -1;
  41. // course i是某些course的prerequisites
  42. if (map.containsKey(i)) {
  43. for (int j : map.get(i)) {
  44. if (!canFinishDFS(map, visit, j)) {
  45. return false;
  46. }
  47. }
  48. }
  49. visit[i] = 1;
  50. return true;
  51. }

Course Schedule II

There are a total of n courses you have to take, labeled from 0 to n - 1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.

There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.

For example:

2, [[1,0]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]

4, [[1,0],[2,0],[3,1],[3,2]]

There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is[0,2,1,3].

Note:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.

click to show more hints.

Hints:

  1. This problem is equivalent to finding the topological order in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses.
  2. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort.
  3. Topological sort could also be done via BFS.

参考:LeetCode 207 Course Schedule

只是加了一句话而已,用于保存结果。注意prerequisites为空的时候,任意输出一组结果即可。

  1. public int[] findOrder(int numCourses, int[][] prerequisites) {
  2. // 参数检查
  3. if (prerequisites == null) {
  4. throw new IllegalArgumentException();
  5. }
  6. int len = prerequisites.length;
  7. if (len == 0) {
  8. int[] seq = new int[numCourses];
  9. for (int i = 0; i < seq.length; i++) {
  10. seq[i] = i;
  11. }
  12. return seq;
  13. }
  14. int[] seq = new int[numCourses];
  15. int c = 0;
  16. // 记录每个course的prerequisites的数量
  17. int[] pCounter = new int[numCourses];
  18. for (int i = 0; i < len; i++) {
  19. pCounter[prerequisites[i][0]]++;
  20. }
  21. // 用队列记录可以直接访问的course
  22. LinkedList<Integer> queue = new LinkedList<Integer>();
  23. for (int i = 0; i < numCourses; i++) {
  24. if (pCounter[i] == 0) {
  25. queue.add(i);
  26. }
  27. }
  28. // 取出队列的course,判断
  29. int numNoPre = queue.size();
  30. while (!queue.isEmpty()) {
  31. int top = queue.remove();
  32. // 保存结果 +_+
  33. seq[c++] = top;
  34. for (int i = 0; i < len; i++) {
  35. // 该course是某个course的prerequisites
  36. if (prerequisites[i][1] == top) {
  37. pCounter[prerequisites[i][0]]--;
  38. if (pCounter[prerequisites[i][0]] == 0) {
  39. numNoPre++;
  40. queue.add(prerequisites[i][0]);
  41. }
  42. }
  43. }
  44. }
  45. if (numNoPre != numCourses) {
  46. return new int[] {};
  47. }
  48. return seq;
  49. }

Flatten Binary Tree to Linked List

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

For example,
Given

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

The flattened tree should look like:

  1. 1
  2. \
  3. 2
  4. \
  5. 3
  6. \
  7. 4
  8. \
  9. 5
  10. \
  11. 6

click to show hints.


  1. TreeNode prev;
  2. void preorder(TreeNode root) {
  3. if (root == null)
  4. return;
  5. TreeNode left = root.left;
  6. TreeNode right = root.right;
  7. // root
  8. if (prev != null) {
  9. prev.right = root;
  10. prev.left = null;
  11. }
  12. prev = root;
  13. preorder(left);
  14. preorder(right);
  15. }
  16. public void flatten(TreeNode root) {
  17. prev = null;
  18. preorder(root);
  19. }

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. public int maxDepth(TreeNode root) {
  2. if (root == null) {
  3. return 0;
  4. }
  5. int nLeft = maxDepth(root.left);
  6. int nRight = maxDepth(root.right);
  7. return nLeft > nRight ? (nLeft + 1) : (nRight + 1);
  8. }

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.


参考:LeetCode 104 Maximum Depth of Binary Tree

Minimum Depth的定义如下:

这里写图片描述

  1. public int minDepth(TreeNode root) {
  2. if (root == null) {
  3. return 0;
  4. }
  5. if (root.left == null && root.right == null) {
  6. return 1;
  7. } else if (root.left != null && root.right == null) {
  8. return minDepth(root.left) + 1;
  9. } else if (root.left == null && root.right != null) {
  10. return minDepth(root.right) + 1;
  11. }
  12. return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
  13. }

Number of Islands

Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example 1:

  1. 11110
  2. 11010
  3. 11000
  4. 00000

Answer: 1

Example 2:

  1. 11000
  2. 11000
  3. 00100
  4. 00011

Answer: 3

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


dfs,遍历过的grid如果是’1’,变成其它字符。

  1. int mx, my;
  2. public int numIslands(char[][] grid) {
  3. if (grid == null || grid.length == 0 || grid[0].length == 0) {
  4. return 0;
  5. }
  6. mx = grid.length;
  7. my = grid[0].length;
  8. int rt = 0;
  9. for (int x = 0; x < mx; x++) {
  10. for (int y = 0; y < my; y++) {
  11. if (grid[x][y] != '1') {
  12. continue;
  13. }
  14. rt++;
  15. dfs(grid, x, y);
  16. }
  17. }
  18. return rt;
  19. }
  20. void dfs(char[][] grid, int x, int y) {
  21. if (x < 0 || x >= mx || y < 0 || y >= my) {
  22. return;
  23. }
  24. if (grid[x][y] == '1') {
  25. grid[x][y] = '2';
  26. dfs(grid, x + 1, y);
  27. dfs(grid, x - 1, y);
  28. dfs(grid, x, y + 1);
  29. dfs(grid, x, y - 1);
  30. }
  31. }

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,

  1. 5
  2. / \
  3. 4 8
  4. / / \
  5. 11 13 4
  6. / \ \
  7. 7 2 1

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


  1. boolean hasPath;
  2. public boolean hasPathSum(TreeNode root, int sum) {
  3. if (root == null) {
  4. return false;
  5. }
  6. hasPath = false;
  7. help(root, 0, sum);
  8. return hasPath;
  9. }
  10. void help(TreeNode node, int cur, int sum) {
  11. cur += node.val;
  12. boolean isLeaf = (node.left == null) && (node.right == null);
  13. if (cur == sum && isLeaf) {
  14. hasPath = true;
  15. }
  16. if (node.left != null) {
  17. help(node.left, cur, sum);
  18. }
  19. if (node.right != null) {
  20. help(node.right, cur, sum);
  21. }
  22. cur -= node.val;
  23. }

更简洁的做法:

  1. public boolean hasPathSum2(TreeNode root, int sum) {
  2. if (root == null) {
  3. return false;
  4. }
  5. if (root.left == null && root.right == null) {
  6. return root.val == sum;
  7. }
  8. return (root.left != null && hasPathSum2(root.left, sum - root.val))
  9. || (root.right != null && hasPathSum2(root.right, sum
  10. - root.val));
  11. }

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,

  1. 5
  2. / \
  3. 4 8
  4. / / \
  5. 11 13 4
  6. / \ / \
  7. 7 2 5 1

return

  1. [
  2. [5,4,11,2],
  3. [5,8,4,5]
  4. ]

  1. List<List<Integer>> result;
  2. List<Integer> path;
  3. int sum;
  4. public List<List<Integer>> pathSum(TreeNode root, int sum) {
  5. result = new ArrayList<List<Integer>>();
  6. path = new ArrayList<Integer>();
  7. this.sum = sum;
  8. if (root == null) {
  9. return result;
  10. }
  11. help(root, 0);
  12. return result;
  13. }
  14. void help(TreeNode node, int cur) {
  15. cur += node.val;
  16. path.add(node.val);
  17. boolean isLeaf = (node.left == null) && (node.right == null);
  18. if (cur == sum && isLeaf) {
  19. result.add(new ArrayList<Integer>(path));
  20. }
  21. if (node.left != null) {
  22. help(node.left, cur);
  23. }
  24. if (node.right != null) {
  25. help(node.right, cur);
  26. }
  27. cur -= node.val;
  28. path.remove(path.size() - 1);
  29. }

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:

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 TreeLinkNode {
  2. int val;
  3. TreeLinkNode left, right, next;
  4. TreeLinkNode(int x) {
  5. val = x;
  6. }
  7. }
  8. public void connect(TreeLinkNode root) {
  9. if (root == null) {
  10. return;
  11. }
  12. if (root.left != null && root.right != null) {
  13. root.left.next = root.right;
  14. }
  15. if (root.next != null && root.next.left != null) {
  16. root.right.next = root.next.left;
  17. }
  18. connect(root.left);
  19. connect(root.right);
  20. }

Same Tree

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

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


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

Symmetric Tree

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

For example, this binary tree is symmetric:

  1. 1
  2. / \
  3. 2 2
  4. / \ / \
  5. 3 4 4 3

But the following is not:

  1. 1
  2. / \
  3. 2 2
  4. \ \
  5. 3 3

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

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


递归:

  1. // recursively
  2. public boolean isSymmetric(TreeNode root) {
  3. if (root == null) {
  4. return true;
  5. }
  6. return isSymmetric(root.left, root.right);
  7. }
  8. boolean isSymmetric(TreeNode p, TreeNode q) {
  9. if (p == null && q == null) {
  10. return true;
  11. } else if (p == null || q == null) {
  12. return false;
  13. }
  14. return p.val == q.val && isSymmetric(p.left, q.right)
  15. && isSymmetric(p.right, q.left);
  16. }

迭代:

  1. // iteratively
  2. public boolean isSymmetric2(TreeNode root) {
  3. if (root == null) {
  4. return true;
  5. }
  6. Deque<TreeNode> deque = new LinkedList<TreeNode>();
  7. if (root.left == null && root.right == null) {
  8. return true;
  9. } else if (root.left == null || root.right == null) {
  10. return false;
  11. } else {
  12. deque.addLast(root.left);
  13. deque.addLast(root.right);
  14. }
  15. while (deque.size() != 0) {
  16. TreeNode p = deque.pop();
  17. TreeNode q = deque.pop();
  18. if (p.val != q.val) {
  19. return false;
  20. }
  21. if (p.left == null && q.right == null) {
  22. // do nothing
  23. } else if (p.left == null || q.right == null) {
  24. return false;
  25. } else {
  26. deque.addLast(p.left);
  27. deque.addLast(q.right);
  28. }
  29. if (p.right == null && q.left == null) {
  30. // do nothing
  31. } else if (p.right == null || q.left == null) {
  32. return false;
  33. } else {
  34. deque.addLast(p.right);
  35. deque.addLast(q.left);
  36. }
  37. }
  38. return true;
  39. }

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. 1
  2. / \
  3. 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.


参考:Sum Root to Leaf Numbers

这里写图片描述

  1. int sumNumbers(TreeNode root, int parentval) {
  2. if (root == null) {
  3. return 0;
  4. }
  5. int p = parentval * 10 + root.val;
  6. if (root.left == null && root.right == null) {
  7. return p;
  8. }
  9. return sumNumbers(root.left, p) + sumNumbers(root.right, p);
  10. }

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:

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


验证一棵树是否为BST,只需要验证中序遍历序列是否是递增的。

  1. boolean failed = false;
  2. // 要用long,而不是int
  3. // 否则涉及到Integer.MIN_VALUE的用例会出现错误
  4. // 比如{Integer.MIN_VALUE}这个用例会错误
  5. long last = Long.MIN_VALUE;
  6. public boolean isValidBST(TreeNode root) {
  7. if (root == null) {
  8. return true;
  9. }
  10. inorder(root);
  11. return !failed;
  12. }
  13. private void inorder(TreeNode root) {
  14. if (root == null || failed) {
  15. return;
  16. }
  17. // 左
  18. inorder(root.left);
  19. // 中,相当于中序遍历中的打印操作
  20. // 只采用了一个变量,所以空间复杂度是O(1)
  21. // 传统的做法是建立一个ArrayList,然后判断中序遍历是否是递增的,但是空间复杂度是O(n)
  22. if (last >= root.val) {
  23. failed = true;
  24. }
  25. last = root.val;
  26. // 右
  27. inorder(root.right);
  28. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注