[算法相关] Leetcode__Maximum depth

 

104. Maximum Depth of Binary Tree


 
Total Accepted: 111336  Total Submissions: 238298  Difficulty: Easy

 

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.

 

Subscribe to see which companies asked this questio

这题困了我我挺长时间,没做过这种类型的,二叉树什么的不清楚是怎么回事。这两天在补~

运行成功的代码如下:

public class Solution {
    public int maxDepth(TreeNode root) {
        int depth = 0;
        if(root != null){
            int leftDepth = maxDepth(root.left);
            int rightDepth = maxDepth(root.right);
            depth ++;
            if(leftDepth < rightDepth){
                depth = depth + rightDepth;
            }else{
                depth = depth + leftDepth;
            }
        }
        return depth;
    }
}
预计还可以优化!
而后看到这下面这种解法,这种解法的巧妙之处在于把上述的意思,通过一句话来表示:
public class Solution {
    public int maxDepth(TreeNode root) {

        return (root == null)?0:Math.max(1+maxDepth(root.left),1+maxDepth(root.right));
    }//如果根节点为空,返回零,否则返回其左子树或是右子树的最高度。
}
另附我在一个地方找到的二叉树构建用例,用于做测试,经验证是可行的:
import java.util.LinkedList;
import java.util.List;



/**
 * 功能:把一个数组的值存入二叉树中,然后进行3种方式的遍历
 * 
 * 参考资料0:数据结构(C语言版)严蔚敏
 * 
 * 参考资料1:http://zhidao.baidu.com/question/81938912.html
 * 
 * 参考资料2:http://cslibrary.stanford.edu/110/BinaryTrees.html#java
 *
 * 参考资料3:http://ocaicai.iteye.com/blog/1047397
 * 
 * @author sunbinbin@zjut.edu.cn @date: 2016-01-08
 * 
 */
public class BinaryTree {

	private int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 ,10,11,12,12,12,12,14,15,16,14,15,16,17,18,19};
	private static List<Node> nodeList = null;

	/**
	 * 内部类:节点
	 * 
	 * @author ocaicai@yeah.net @date: 2016-1-7
	 * 
	 */
	private static class Node {
		Node leftChild;
		Node rightChild;
		int data;

		Node(int newData) {
			leftChild = null;
			rightChild = null;
			data = newData;
		}
	}

	public void createBinTree() {
		nodeList = new LinkedList<Node>();
		// 将一个数组的值依次转换为Node节点
		for (int nodeIndex = 0; nodeIndex < array.length; nodeIndex++) {
			nodeList.add(new Node(array[nodeIndex]));
		}
		// 对前lastParentIndex-1个父节点按照父节点与孩子节点的数字关系建立二叉树
		for (int parentIndex = 0; parentIndex < array.length / 2 - 1; parentIndex++) {
			// 左孩子
			nodeList.get(parentIndex).leftChild = nodeList
					.get(parentIndex * 2 + 1);
			// 右孩子
			nodeList.get(parentIndex).rightChild = nodeList
					.get(parentIndex * 2 + 2);
		}
		// 最后一个父节点:因为最后一个父节点可能没有右孩子,所以单独拿出来处理
		int lastParentIndex = array.length / 2 - 1;
		// 左孩子
		nodeList.get(lastParentIndex).leftChild = nodeList
				.get(lastParentIndex * 2 + 1);
		// 右孩子,如果数组的长度为奇数才建立右孩子
		if (array.length % 2 == 1) {
			nodeList.get(lastParentIndex).rightChild = nodeList
					.get(lastParentIndex * 2 + 2);
		}
	}

	/**
	 * 先序遍历
	 * 
	 * 这三种不同的遍历结构都是一样的,只是先后顺序不一样而已
	 * 
	 * @param node
	 *            遍历的节点
	 */
	public static void preOrderTraverse(Node node) {
		if (node == null)
			return;
		System.out.print(node.data + " ");
		preOrderTraverse(node.leftChild);
		preOrderTraverse(node.rightChild);
	}

	/**
	 * 中序遍历
	 * 
	 * 这三种不同的遍历结构都是一样的,只是先后顺序不一样而已
	 * 
	 * @param node
	 *            遍历的节点
	 */
	public static void inOrderTraverse(Node node) {
		if (node == null)
			return;
		inOrderTraverse(node.leftChild);
		System.out.print(node.data + " ");
		inOrderTraverse(node.rightChild);
	}

	/**
	 * 后序遍历
	 * 
	 * 这三种不同的遍历结构都是一样的,只是先后顺序不一样而已
	 * 
	 * @param node
	 *            遍历的节点
	 */
	public static void postOrderTraverse(Node node) {
		if (node == null)
			return;
		postOrderTraverse(node.leftChild);
		postOrderTraverse(node.rightChild);
		System.out.print(node.data + " ");
	}
	public int maxDepth(Node root) {
		int depth = 0;
		if(root != null){
			int leftDepth = maxDepth(root.leftChild);
			int rightDepth = maxDepth(root.rightChild);
			depth ++;
			if(leftDepth < rightDepth){
				depth = depth + rightDepth;
			}else{
				depth = depth + leftDepth;
			}
		}
		return depth; 
	} 
	public static void main(String[] args) {
		BinaryTree binTree = new BinaryTree();
		binTree.createBinTree();
		// nodeList中第0个索引处的值即为根节点
		Node root = nodeList.get(0);
		int a=binTree.maxDepth(root);
		System.out.println("a="+a);
		
		System.out.println("先序遍历:");
		preOrderTraverse(root);
		System.out.println();

		System.out.println("中序遍历:");
		inOrderTraverse(root);
		System.out.println();

		System.out.println("后序遍历:");
		postOrderTraverse(root);
	}

}
其中的几种遍历方法,我没删除!

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
KMP算法是一种字符串匹配算法,用于在一个文本串S内查找一个模式串P的出现位置。它的时间复杂度为O(n+m),其中n为文本串的长度,m为模式串的长度。 KMP算法的核心思想是利用已知信息来避免不必要的字符比较。具体来说,它维护一个next数组,其中next[i]表示当第i个字符匹配失败时,下一次匹配应该从模式串的第next[i]个字符开始。 我们可以通过一个简单的例子来理解KMP算法的思想。假设文本串为S="ababababca",模式串为P="abababca",我们想要在S中查找P的出现位置。 首先,我们可以将P的每个前缀和后缀进行比较,得到next数组: | i | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | | --- | - | - | - | - | - | - | - | - | | P | a | b | a | b | a | b | c | a | | next| 0 | 0 | 1 | 2 | 3 | 4 | 0 | 1 | 接下来,我们从S的第一个字符开始匹配P。当S的第七个字符和P的第七个字符匹配失败时,我们可以利用next[6]=4,将P向右移动4个字符,使得P的第五个字符与S的第七个字符对齐。此时,我们可以发现P的前五个字符和S的前五个字符已经匹配成功了。因此,我们可以继续从S的第六个字符开始匹配P。 当S的第十个字符和P的第八个字符匹配失败时,我们可以利用next[7]=1,将P向右移动一个字符,使得P的第一个字符和S的第十个字符对齐。此时,我们可以发现P的前一个字符和S的第十个字符已经匹配成功了。因此,我们可以继续从S的第十一个字符开始匹配P。 最终,我们可以发现P出现在S的第二个位置。 下面是KMP算法的C++代码实现:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值