zoukankan      html  css  js  c++  java
  • 二叉树总结

     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);
    }
  • 相关阅读:
    mysql复制那点事
    全排列问题
    56. Merge Interval
    2. Add Two Numbers
    20. Valid Parentheses
    121. Best Time to Buy and Sell Stock
    120. Triangle
    96. Unique Binary Search Trees
    91. Decode Ways
    72. Edit Distance
  • 原文地址:https://www.cnblogs.com/evenleee/p/10324214.html
Copyright © 2011-2022 走看看