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;
    }

相关文章:

  • 2022-01-09
  • 2022-12-23
  • 2021-06-25
  • 2022-02-05
  • 2021-09-15
  • 2021-07-16
猜你喜欢
  • 2021-06-29
  • 2021-12-13
  • 2021-10-01
  • 2022-12-23
  • 2022-12-23
  • 2021-09-17
  • 2021-06-04
相关资源
相似解决方案