题目
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.
方法一
后序遍历树,使用递归,分别遍历左右子树,并将记录左右子树的高度。返回的是高度较小的。public int minDepth(TreeNode root) { if (root == null) { return 0; } if (root.left == null && root.right == null) { return 1; } int left = minDepth(root.left); int right = minDepth(root.right); if (left == 0) { return right + 1; } else if (right == 0) { return left + 1; } else { return Math.min(left, right) + 1; } }
方法二
后序遍历,使用栈来实现。public int minDepth(TreeNode root) { if (root == null) { return 0; } Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode curNode = root; TreeNode lastNode = null; int min = Integer.MAX_VALUE; while (curNode != null || !stack.isEmpty()) { while (curNode != null) { stack.push(curNode); curNode = curNode.left; } curNode = stack.peek(); if ( curNode.right == null || curNode.right == lastNode) { if (curNode.left == null && curNode.right == null) { if (min > stack.size()) { min = stack.size(); } } lastNode = curNode; stack.pop(); curNode = null; } else{ curNode = curNode.right; } } return min; }