Binary tree (LeetCode) C++ related knowledge code series 1

0. Maximum depth of binary tree

     原题目:Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

     Method: When finding the maximum depth, you only need to compare the depth of the left and right subtrees, and take the larger one + 1.

    C++ code:

class Solution

{
public:

    int minDepth(TreeNode *root){

        if(root==Null) return 0;
        int l=minDepth(root->left);
        int r=minDepth(root->right);
        if(l==0||r==0)
            return 1+l+r;
        return 1+min(l,r);
    }
    
};

1. Minimum depth of binary tree

     原题目:Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

    Method: When finding the minimum depth, it is necessary to distinguish between the double subtree and the single subtree. In the case of the double subtree, the lower depth is +1, and the single subtree (that is, when one of the left and right subtrees is empty) is the larger depth +1

    C++ code:

class Solution{

public:
    int maxDepth(TreeNode *root){

        if (root==NULL)
        {
            return 0;
        }
        int l=maxDepth(root->left);
        int r=maxDepth(root->right);
        return 1+max(l,r);

    }

};

2、Given a binary tree, return the postorder traversal of its nodes' values.

       For example:
  Given binary tree{1,#,2,3},

   1
    \
     2
    /
   3

 

  return[3,2,1].

  Note: Recursive solution is trivial, could you do it iteratively?

   Method: Post-order traversal, use the vector stack to do it, first push the parent node onto the stack, then push the right child onto the stack, and the left child onto the stack. Then when returning, the post-order traversal values ​​can be output in reverse order.

class Solution{
    public:
        void postOrder(TreeNode *root,vector<int>&vec){
            if (root!=NULL)
            {
                postOrder(root->left,vec);
                postOrder(root->right,vec);
                vec.push_back(root->val);
            }
        }
        vector<int>postorderTraversal(TreeNode *root){
            vector<int> vec;
            postOrder (root, vec);
            return vec;
        }

};

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325262077&siteId=291194637