二叉树的深度 - Java

二叉树的深度

题目描述

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

输入

{1,2,3,4,5,#,6,#,#,7}

返回值

4

一看到题目其实我就想到要用递归了,但是一直想怎么也想不出来。真的,打代码最忌空想,其实你开始敲,思路就慢慢出来了。以后真就要改掉这个坏习惯。

方法一(递归,代码量很少,最重要的是解决思路)
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    
    
    public int TreeDepth(TreeNode root) {
    
    
        // 到了根节点就返回0
        if(root == null)
            return 0;
        // 遍历左节点
        int left = TreeDepth(root.left);
        // 遍历右节点
        int right = TreeDepth(root.right);
        // 深度+1
        return Math.max(left,right)+1;
    }
}
方法二(非递归),利用队列,count是当前的节点,nextcount是当前深度总的节点。【总是要遍历到当前深度的最后一个节点,深度才加1】
import java.util.LinkedList;
import java.util.Queue;
 public int TreeDepth1(TreeNode root) {
    
    
    if(root==null) {
    
    
      return 0;
    }
    Queue<TreeNode> q=new LinkedList<TreeNode>();
    q.add(root);
    int d=0,count=0,nextcount=q.size();
    while(q.size()!=0) {
    
    
      TreeNode t=q.poll();
      count++;
      if(t.left!=null) {
    
    
           q.add(t.left);
      }
      if(t.right!=null) {
    
    
           q.add(t.right);
      }
      // 当把当前深度的所有节点都遍历过后,深度加一,跳到下一深度
      if(count==nextcount) {
    
    
           d++;
           // 当前节点重置
           count=0;
           nextcount=q.size(); // 保存最后节点
      }
    }
    return d;
}

猜你喜欢

转载自blog.csdn.net/weixin_43957211/article/details/114921479