zoukankan      html  css  js  c++  java
  • 剑指offer系列——38.二叉树的深度

    Q:输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
    A:
    这是很典型的二叉树递归问题。

        int TreeDepth(TreeNode* pRoot){
            if (pRoot == nullptr)
                return 0;
            int l = TreeDepth(pRoot->left);
            int r = TreeDepth(pRoot->right);
            return l > r ? l + 1 : r + 1;
        }
    

    层次遍历方法:

        int TreeDepth(TreeNode* pRoot) {
            if (!pRoot) return 0;
            queue<TreeNode*> que;
            que.push(pRoot);int depth=0;
            while (!que.empty()) {
                int size=que.size();
                depth++;
                for (int i=0;i<size;i++) {      //一次处理一层的数据
                    TreeNode *node=que.front();
                    que.pop();
                    if (node->left) que.push(node->left);
                    if (node->right) que.push(node->right);
                }
            }
            return depth;
        }
    
  • 相关阅读:
    VSCode C++ 主题
    Linux 软连接应用
    Python 调用 C 动态库
    Qt 打包程序
    Qt 样式修改
    libusb 批传输的使用方法
    Qt 数据库操作
    Qt 调用第三方库
    CS 调用 C 动态库
    Qt 串口操作
  • 原文地址:https://www.cnblogs.com/xym4869/p/12326775.html
Copyright © 2011-2022 走看看