zoukankan      html  css  js  c++  java
  • 剑指offer(三十八):二叉树的深度

    题目描述

    输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
    思路:本题可以使用递归和非递归两种算法,非递归可以使用层次遍历
    C++递归实现:
    class Solution {
    public:
        int TreeDepth(TreeNode* pRoot)
        {
            if(!pRoot)
                return 0;
            int leftHigh = TreeDepth(pRoot->left)+1;
            int rightHigh = TreeDepth(pRoot->right)+1;
            int high = leftHigh>rightHigh?leftHigh:rightHigh;
            return high;
        }
    };

    java层次遍历实现:

    使用了两个队列,一个用来存储结点,一个用来存储当前是第几层

    import java.util.*;
    public class Solution {
        public int TreeDepth(TreeNode root) {
            if(root == null)
                return 0;
            Queue<TreeNode> treeQ = new LinkedList<>();
            Queue<Integer> highQ = new LinkedList<>();
            TreeNode p;
            int high = 1;
            treeQ.add(root);
            highQ.add(high);
            while(!treeQ.isEmpty()){
                p = treeQ.poll();
                if(p!=null){
                    high = highQ.poll();
                    if(p.left != null){
                        treeQ.add(p.left);
                        highQ.add(high+1);
                    }
                    if(p.right != null){
                        treeQ.add(p.right);
                        highQ.add(high+1);
                    }
                }
            }
            return high;
        }
    }

    import java.util.*;
    public class Solution {
        public int TreeDepth(TreeNode root) {
            if(root == null)
                return 0;
            Queue<TreeNode> Q = new LinkedList<>();
            int high = 0;
            int curNodeNum =0;
            int levelNodeNum = 1;
            TreeNode p;
            
            Q.add(root);
            
            while(!Q.isEmpty()){
                p = Q.poll();
                ++curNodeNum;         //当前结点个数加1 
                if(p.left != null)
                    Q.add(p.left);
                if(p.right != null)
                    Q.add(p.right);
                if(curNodeNum == levelNodeNum){  //这一层遍历结束
                    levelNodeNum = Q.size();//此时队列中结点个数即该层的结点个数
                    curNodeNum = 0;
                    ++high;
                }
            }
            return high;
        }
    }

  • 相关阅读:
    Spark SQL学习笔记
    《空空》陈粒
    支持向量机
    p.Value越显著,X变量越重要嘛?
    回归的武林绝学
    Neural Collaborative Filtering论文笔记
    make 学习笔记
    『并发包入坑指北』之阻塞队列
    线程池中你不容错过的一些细节
    利用策略模式优化过多 if else 代码
  • 原文地址:https://www.cnblogs.com/ttzz/p/13449468.html
Copyright © 2011-2022 走看看