二叉树的深度

来源:互联网 发布:利用淘宝规则赚钱 编辑:程序博客网 时间:2024/06/03 05:03

输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。


BFS:

/*public class TreeNode {    int val = 0;    TreeNode left = null;    TreeNode right = null;    public TreeNode(int val) {        this.val = val;    }};*/import java.util.*;public class Solution {    public int height = 0;    public Queue<TreeNode> q  = new LinkedList<TreeNode>();    public Queue<TreeNode> qq = new LinkedList<TreeNode>();    public int TreeDepth(TreeNode pRoot)    {        if(pRoot == null)   return 0;        q.add(pRoot);        bfs(pRoot);        return height;    }    public void bfs(TreeNode pRoot){        while(!q.isEmpty()){            TreeNode p = q.remove();            if(p.left != null)                qq.add(p.left);            if(p.right != null)                qq.add(p.right);            if(q.isEmpty()){                q = qq;                qq = new LinkedList<TreeNode>();                height ++;            }        }    }}

DFS:

import java.util.*;public class Solution {    public int TreeDepth(TreeNode pRoot)    {        if(pRoot == null)   return 0;        int h1 = TreeDepth(pRoot.left);        int h2 = TreeDepth(pRoot.right);        return 1 + Math.max(h1, h2);    }}
0 0
原创粉丝点击