递归/深度优先搜索, 维持一个全局变量记录深度node
时间复杂度O(n)code
//递归 class Solution { int maxDepth = 0; public int maxDepth(TreeNode root) { if (root == null) { return 0; } helper(root, 1); return maxDepth; } private void helper(TreeNode node, int cur) { if (node == null) { return; } maxDepth = Math.max(cur, maxDepth); helper(node.left, cur + 1); helper(node.right, cur +1); } }
分治法递归
时间复杂度O(n)io
//分治 class Solution { public int maxDepth(TreeNode root) { int max = 0; if (root == null) { return max; } int left = maxDepth(root.left); int right = maxDepth(root.right); max = Math.max(left, right) + 1; return max; } }
广度优先搜索的方法, 用queue来记录树的节点class
时间复杂度O(n) 空间复杂度O(log n)变量
//BFS class Solution { int maxDepth = 0; public int maxDepth(TreeNode root) { if (root == null) { return 0; } int depth = 0; Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); while (!queue.isEmpty()) { int size = queue.size(); for (int i = 0; i <size; i++) { TreeNode cur = queue.poll(); if (cur.left != null) { queue.offer(cur.left); } if (cur.right != null) { queue.offer(cur.right); } } depth++; } return depth; } }