https://blog.csdn.net/luckyxiaoqiang/article/details/7518888
struct TreeNode { int val; TreeNode* left; TreeNode* right; };
1、求二叉树中节点的个数
int getTreeNodeNum(TreeNode* root) { if (root == NULL) return 0; return getTreeNodeNum(root->left) + getTreeNodeNum(root->right) + 1; }
2、求二叉树的深度
int getTreeDepth(TreeNode* root) { if(root == NULL) return 0; int leftDepth = getTreeDepth(root->left); int rightDepth = getTreeDepth(root->right); return leftDepth > rightDepth ? (leftDepth + 1) : (rightDepth + 1); }
3、二叉树的前序遍历
void preTreeNode(TreeNode* root) { if (root == NULL) return; cout << root->val << endl; preTreeNode(root->left); preTreeNode(root->right); }
4、求二叉树叶子节点的个数
int getLeafNodeNum(TreeNode* root) { if (root == NULL) return 0; if (root->left == NULL && root->right == NULL) return 1; return getLeafNodeNum(root->left) + getLeafNodeNum(root->right); }