标签:
就recursive做,简单题
public class Solution { public int minDepth(TreeNode root) { if(root==null) return 0; if (root.left==null && root.right==null) return 1; if(root.left==null) return 1+minDepth(root.right); if(root.right==null) return 1+minDepth(root.left); return 1+ Math.min(minDepth(root.left), minDepth(root.right)); } }
非recursive做法就是binary tree level order traversal的应用小拓展一下, 这种做法逻辑非常清晰,一般可以见雍正
public int minDepth(TreeNode root) { if(root==null) return 0; int res=1, curNum=1,nextNum=0; LinkedList<TreeNode> q = new LinkedList<TreeNode>(); q.add(root); while(!q.isEmpty()){ curNum--; TreeNode n = q.poll(); if(n.left==null && n.right==null) return res; if(n.left!=null){ nextNum++; q.add(n.left); } if(n.right!=null){ nextNum++; q.add(n.right); } if(curNum==0){ res++; curNum=nextNum; nextNum=0; } } return res; }
标签:
原文地址:http://www.cnblogs.com/jiajiaxingxing/p/4565054.html