二叉树的深度_JAVA_简单

二叉树的深度

http://www.nowcoder.com/questionTerminal/435fb86331474282a3499955f0a41e8b

递归

  • 当前节点深度为左右孩子的最大深度 + 1

    public class Solution {
      public int TreeDepth(TreeNode root) {
          if(root == null) {
              return 0;
          }
    
          return Math.max(TreeDepth(root.left), TreeDepth(root.right)) + 1;
      }
    }

非递归

  • 层次遍历树,每一层+1

    import java.util.*;
    public class Solution {
      public int TreeDepth(TreeNode root) {
          if(root == null) {
              return 0;
          }
    
          Queue<TreeNode> queue = new LinkedList();
          int depth = 0;
          queue.offer(root);
    
          // 层次遍历
          while(!queue.isEmpty()) {
              depth++;
              int length = queue.size();
              // 出该层节点,且压入下一层
              while(length-- > 0) {
                  TreeNode node = queue.poll();
                  if(node.left != null) {
                      queue.offer(node.left);
                  }
                  if(node.right != null) {
                      queue.offer(node.right);
                  }
              }
          }
    
          return depth;
      }
    }
全部评论

相关推荐

鬼迹人途:你去投一投尚游游戏,服务器一面,第一个图算法,做完了给你一个策略题,你给出方案他就提出低概率问题,答不上当场给你挂
点赞 评论 收藏
分享
07-02 13:52
武汉大学 golang
骗你的不露头也秒
牛客87776816...:😃查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务