遞歸/深度優先搜索, 維持一個全局變量記錄深度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; } }