赞
踩
Queue<TreeNode> queue = new LinkedList<>()
while(!queue.isEmpty())
class Solution {
List<Integer> res = new ArrayList<>();
public int maxDepth(TreeNode root) {
int depth = 0;
if(root==null){
return depth;
}
// 借助队列
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
int len = queue.size();
// path
while(len>0){
TreeNode nowNode = queue.poll();
if(nowNode.left != null) queue.offer(nowNode.left);
if(nowNode.right != null) queue.offer(nowNode.right);
len--;
}
depth++;
}
return depth;
}
}
public class maxDepth {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public static TreeNode build(String str){
if(str == null || str.length()==0){
return null;
}
String input = str.replace("[","");
input = input.replace("]","");
String[] parts = input.split(",");
Integer[] nums = new Integer[parts.length];
for(int i = 0 ; i < parts.length;i++){
if(!parts[i].equals("null")){
nums[i] = Integer.parseInt(parts[i]);
}else{
nums[i] = null;
}
}
Queue<TreeNode> queue = new LinkedList<>();
TreeNode root = new TreeNode(nums[0]);
queue.offer(root);
int index = 1;
while(!queue.isEmpty()&& index<parts.length){
TreeNode node = queue.poll();
if(index<nums.length && nums[index]!=null){
node.left = new TreeNode(nums[index]);
queue.offer(node.left);
}
index++;
if(index<nums.length && nums[index]!=null){
node.right = new TreeNode(nums[index]);
queue.offer(node.right);
}
index++;
}
return root;
}
public static int maxDepth(TreeNode root) {
int depth = 0;
if(root==null){
return depth;
}
// 借助队列
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
int len = queue.size();
// path
while(len>0){
TreeNode nowNode = queue.poll();
if(nowNode.left != null) queue.offer(nowNode.left);
if(nowNode.right != null) queue.offer(nowNode.right);
len--;
}
depth++;
}
return depth;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
TreeNode root = build(input);
System.out.println("结果是"+maxDepth(root));
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。