二叉树

生成leetcode二叉树

在刷leetcode很多树题目的时候经常遇到这种情况:

示例:
二叉树:[3,9,20,null,null,15,7],

  1. 3
  2. / \
  3. 9 20
  4. / \
  5. 15 7

发现测试的例子是一个数组 ,输入的数据是一个树形结构,每次手动的去创建比较麻烦,写了一个数组到树的一个小工具

由于其中有null的情况所以用的是装箱类,实现过程也比较简单,就是先创建根节点然后在创建左右子树,在创建左右子树的时候依次的把左右子树加入到一个队列,如果为空就跳过,每次从队列中取出一个节点依次的把左右子树加入到一个队列,这样一直遍历下去直到把数组遍历完了。

  1. public class TreeNode {
  2. int val;
  3. TreeNode left;
  4. TreeNode right;
  5. TreeNode() {}
  6. TreeNode(int val) {
  7. this(val,null,null);
  8. }
  9. TreeNode(int val, TreeNode left, TreeNode right) {
  10. this.val = val;
  11. this.left = left;
  12. this.right = right;
  13. }
  14. /**
  15. * 构建 leetcode 二叉树
  16. * @param nums
  17. * */
  18. public static TreeNode generateTreeNode(Integer[] nums) {
  19. if(nums==null||nums.length==0) {
  20. return null;
  21. }
  22. int len=nums.length;
  23. int index=0;
  24. //初始化第一个节点
  25. TreeNode head=new TreeNode(nums[index]);
  26. Deque<TreeNode> nodeQueue = new LinkedList<>();
  27. //插入元素,失败返回null或false
  28. nodeQueue.offer(head);
  29. TreeNode cur;
  30. while (index<len){
  31. index++;
  32. if (index>=len) {
  33. return head;
  34. }
  35. //移除元素
  36. cur = nodeQueue.poll();
  37. Integer left=nums[index];
  38. if (left!=null){
  39. cur.left=new TreeNode(left);
  40. //插入
  41. nodeQueue.offer(cur.left);
  42. }
  43. index++;
  44. if (index>=len) {
  45. return head;
  46. }
  47. Integer right=nums[index];
  48. if (right!=null){
  49. cur.right=new TreeNode(right);
  50. //插入
  51. nodeQueue.offer(cur.right);
  52. }
  53. }
  54. return head;
  55. }
  56. public static void main(String[] args) {
  57. Integer[] data1={3,9,20,null,null,15,7};
  58. TreeNode node = generateTreeNode(data1);
  59. }
  60. }

BFS和DFS

深度优先遍历(DFS)

  • 递归写法(容易内存溢出)
  1. /**
  2. * DFS 深度优先遍历 (递归)
  3. * @param root
  4. * */
  5. public static void dfsPreOrderTraverse(TreeNode root) {
  6. if (root == null)
  7. {
  8. return;
  9. }
  10. System.out.print(root.val + " ");
  11. dfsPreOrderTraverse(root.left);
  12. dfsPreOrderTraverse(root.right);
  13. }
  • 栈写法(推荐)
  1. /**
  2. * DFS 深度优先遍历(stack栈)
  3. * @param root
  4. * */
  5. public static void dfsWithStack(TreeNode root){
  6. if(root == null){
  7. return;
  8. }
  9. Stack<TreeNode> stack = new Stack<>();
  10. //进栈
  11. stack.push(root);
  12. while (!stack.isEmpty()){
  13. //出栈
  14. TreeNode node = stack.pop();
  15. System.out.println(node.val);
  16. if(node.right!= null){
  17. stack.push(node.right);
  18. }
  19. if(node.left!= null){
  20. stack.push(node.left);
  21. }
  22. }
  23. }

广度优先遍历(BFS)

  1. public static void bfsTree(TreeNode root){
  2. if(root == null){
  3. return;
  4. }
  5. Queue<TreeNode> queue = new ArrayDeque<>();
  6. //入队
  7. queue.add(root);
  8. while (!queue.isEmpty()){
  9. //出队
  10. int size = queue.size();
  11. TreeNode node = queue.poll();
  12. System.out.println("遍历元素"+node.val);
  13. for (int i = 0; i < size; i++) {
  14. if(node.left != null){
  15. queue.add(node.left);
  16. }
  17. if(node.right != null){
  18. queue.add(node.right);
  19. }
  20. }
  21. }
  22. }
  • 输出
  1. 遍历元素3
  2. 遍历元素9
  3. 遍历元素20
  4. 遍历元素15
  5. 遍历元素7

BFS常用场景:

  • 二叉树层序遍历
  • 求解最短路径问题

层次遍历

层次遍历并记录每层树节点并记录每层树节点(leetcode 102)

  1. /**
  2. * BFS 层次遍历记录每层树的节点
  3. * */
  4. public static List<List<Integer>> bfsSaveTreeNode(TreeNode root){
  5. List<List<Integer>> res =new ArrayList<>();
  6. Queue<TreeNode> queue = new ArrayDeque<>();
  7. if(root!=null){
  8. //入队
  9. queue.add(root);
  10. }
  11. while (!queue.isEmpty()){
  12. //出队
  13. int size = queue.size();
  14. List<Integer> level = new ArrayList<>();
  15. for (int i = 0; i < size; i++) {
  16. TreeNode node = queue.poll();
  17. level.add(node.val);
  18. if(node.left != null){
  19. queue.add(node.left);
  20. }
  21. if(node.right != null){
  22. queue.add(node.right);
  23. }
  24. }
  25. res.add(level);
  26. }
  27. return res;
  28. }
  • 输出
  1. [3]
  2. [9, 20]
  3. [15, 7]

树最大深度

  1. /**
  2. * 获取树的最大深度
  3. * @param root
  4. * */
  5. public static int getTreeDepth(TreeNode root){
  6. int leftDepth = 0;
  7. int rightDepth = 0;
  8. if(root == null){
  9. return 0;
  10. }
  11. if(root.left != null){
  12. leftDepth = getTreeDepth(root.left) + 1;
  13. }
  14. if(root.right != null){
  15. rightDepth = getTreeDepth(root.right) + 1;
  16. }
  17. return Math.max(leftDepth,rightDepth);
  18. }

叶子节点个数

  1. /**
  2. * 求二叉树种叶子节点的个数
  3. *
  4. * @param root
  5. * @return
  6. */
  7. public static int getLeafNum(TreeNode root) {
  8. if (root == null) {
  9. return 0;
  10. }
  11. if (root.left == null && root.right == null) {
  12. return 1;
  13. }
  14. int leftNum = getLeafNum(root.left);
  15. int rightNum = getLeafNum(root.right);
  16. return leftNum + rightNum;
  17. }

K层节点数

  1. /**
  2. * 求第K层节点个数
  3. *
  4. * @param root
  5. * @param k
  6. * @return
  7. */
  8. public static int getNumForKLevel(TreeNode root, int k) {
  9. if (root == null || k < 1) {
  10. return 0;
  11. }
  12. if (k == 1) {
  13. return 1;
  14. }
  15. int leftNum = getNumForKLevel(root.left, k - 1);
  16. int rightNum = getNumForKLevel(root.right, k - 1);
  17. return leftNum + rightNum;
  18. }