Maximum Depth of Binary Tree(java version)

来源:互联网 发布:html5小游戏源码下载 编辑:程序博客网 时间:2024/06/10 19:24

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.

题意是:非递归求二叉树最大深度。

ac代码:


/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int maxDepth(TreeNode root) {       if(root==null)return 0;        Queue<TreeNode> qu=new LinkedList<TreeNode>();        root.val=1;        qu.add(root);        int depth=1;        while(!qu.isEmpty()){        TreeNode tn=qu.peek();        qu.remove();        depth=tn.val;        if(tn.left!=null){        TreeNode t;        t=tn.left;        t.val=tn.val+1;        qu.add(t);        }        if(tn.right!=null){        TreeNode t;        t=tn.right;        t.val=tn.val+1;        qu.add(t);        }         }        return depth;    }}


0 0