⭐️ Preface
✨ Links to previous articles: Conceptual properties of binary trees
In the previous article, we talked about the structure definition of the binary tree, as well as the recursive traversal of the preorder/inorder/postorderBinaryTreeDepth
, and some interface implementations of the binary tree. In this article, we add a binary tree interface . ✨Previous article link: Detailed Explanation of Binary Tree (1)
Prequel:
⭐️Other interfaces of binary tree
// 求二叉树的深度
int BinaryTreeDepth(BinaryTreeNode* root);
BinaryTreeDepth
accomplish:
int BinaryTreeDepth(BinaryTreeNode* root) {
// 空树没有高度直接返回0
if (root == NULL) {
return 0;
}
// 递归获取左子树的高度
int leftTreeDepth = BinaryTreeDepth(root->left);
// 递归获取右子树的高度
int rightTreeDepth = BinaryTreeDepth(root->right);
// 比较左子树和右子树的高度 取较高的同时在加上当前这一层的高度
return leftTreeDepth > rightTreeDepth ? leftTreeDepth + 1 : rightTreeDepth + 1;
}
BinaryTreeDepth
Recursive flowchart: