LeetCode:Minimum Depth of Binary Tree

来源:互联网 发布:dede数据库备份目录 编辑:程序博客网 时间:2024/05/16 06:05

LeetCode第二话,其实中间也写了其他题,但是较为简单,就不赘述了。这道题,一上来,又理解错了,一直以为是用广度优先来一层一层的搜索哪个节点没有两个子节点。结果一测试,当只有两个节点时,结果居然为2,感觉太不可思议了,所以赶紧跑去看看人家怎么理解题目的。就看到这篇http://blog.csdn.net/andrewseu/article/details/28595541

题目为: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.其实人家写的很清楚,求二叉树的最小深度,在这里,最小深度指的是根节点最近叶节点的路径上包含的节点数目

  1. 首先来一个自己YY的版本吧,就是从理解错误的版本上的更改版本。首先声明下我对递归理解还不是特别好,所以选了个非递归的实现方案。大概思路就是,一层一层的搜索叶节点,如果搜索到了就返回层数值。在该方法中,我使用两个栈,其中一个存储现在正在遍历的层数的节点,另外一个存储现在遍历的层数的下一层的节点,每次遍历完一层(该层对应的栈),如果还没找到叶节点,就将结果加1,然后遍历另外一个栈,直到找到叶节点为止。(方法有点笨,哈哈,不过算是个进步的过程吧~)。代码如下:
    /** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int minDepth(TreeNode root) {        int result=0;boolean oneOrTwo;Stack<TreeNode> stack1=new Stack<TreeNode>();Stack<TreeNode> stack2=new Stack<TreeNode>();if(root!=null){stack1.push(root);oneOrTwo=true;}else {return result;}while(!stack1.empty()||!stack2.empty()){if(oneOrTwo){TreeNode t=stack1.pop();if(t.left==null&&t.right==null){result++;return result;}else{if(t.left!=null){stack2.push(t.left);}if(t.right!=null){stack2.push(t.right);}}if(stack1.size()==0){result++;oneOrTwo=!oneOrTwo;}}else {TreeNode t=stack2.pop();if(t.left==null&&t.right==null){result++;return result;}else{if(t.left!=null){stack1.push(t.left);}if(t.right!=null){stack1.push(t.right);}}if(stack2.size()==0){result++;oneOrTwo=!oneOrTwo;}}}return result;    }}
  2. 第二种方法是看网上的递归解法,上面引用的文章中就用的是这种解法,虽然递归其实就是对问题的分解,但是总是觉得理解起来有点奇怪,哈哈~这种解法的基本思路为:递归的返回包括四种情况,第一种是根节点为null,显然结果为0;第二种为只有一个根节点,则结果为1;第三种为,缺少左子树或者右子树,则返回的是有孩子那边的深度;最后一种情况是,左子树和右子树都存在,则需要判定那边的深度小。代码如下:
    /** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int minDepth(TreeNode root) {        if(root==null){return 0;}else if(root.left==null&&root.right==null){return 1;}else {int leftDepth=minDepth(root.left);int rightDepth=minDepth(root.right);if(leftDepth==0){return rightDepth+1;}else if(rightDepth==0){return leftDepth+1;}else{return Math.min(leftDepth, rightDepth)+1;}}    }}
    另外,其实我不用递归的一种想法是,因为递归总是按顺序来遍历子树,例如上面就是先遍历左子树,再遍历右子树,当最小深度在后遍历的子树中,则运算会较慢,所以我觉得一层一层遍历寻找叶节点会比较好,虽然用的方法有点笨,哈哈~不过这道题倒是提醒我该好好复习下深度优先算法和广度优先算法了。


0 0
原创粉丝点击