binary tree | 二叉树基本操作(1)

一、

题目:

655. Print Binary Tree

 

Print a binary tree in an m*n 2D string array following these rules:

  1. The row number m should be equal to the height of the given binary tree.
  2. The column number n should always be an odd number.
  3. The root node's value (in string format) should be put in the exactly middle of the first row it can be put. The column and the row where the root node belongs will separate the rest space into two parts (left-bottom part and right-bottom part). You should print the left subtree in the left-bottom part and print the right subtree in the right-bottom part. The left-bottom part and the right-bottom part should have the same size. Even if one subtree is none while the other is not, you don't need to print anything for the none subtree but still need to leave the space as large as that for the other subtree. However, if two subtrees are none, then you don't need to leave space for both of them.
  4. Each unused space should contain an empty string "".
  5. Print the subtrees following the same rules.

Example 1:

Input:
     1
    /
   2
Output:
[["", "1", ""],
 ["2", "", ""]]

 

Example 2:

Input:
     1
    / \
   2   3
    \
     4
Output:
[["", "", "", "1", "", "", ""],
 ["", "2", "", "", "", "3", ""],
 ["", "", "4", "", "", "", ""]]

 

Example 3:

Input:
      1
     / \
    2   5
   / 
  3 
 / 
4 
Output:

[["",  "",  "", "",  "", "", "", "1", "",  "",  "",  "",  "", "", ""]
 ["",  "",  "", "2", "", "", "", "",  "",  "",  "",  "5", "", "", ""]
 ["",  "3", "", "",  "", "", "", "",  "",  "",  "",  "",  "", "", ""]
 ["4", "",  "", "",  "", "", "", "",  "",  "",  "",  "",  "", "", ""]]

 

Note: The height of binary tree is in the range of [1, 10].

解答:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<string>> printTree(TreeNode* root) {
        if(!root)
            return vector<vector<string>>();
        int h = depthOfTree(root);
        
        int w = (1 << h) - 1;//1<< n; 2 的你次方
       // cout << w << endl; 
        vector<vector<string>> res(h, vector<string>(w, ""));
        
        printBT(res, root, 0, 0, w - 1); 
        return res;
    }
    
private:
    //
    void printBT(vector<vector<string>> & res, TreeNode* root, int h, int begin, int end)
        
    {
        if(!root)
            return;
        int mid = begin + (end - begin) / 2;
        res[h][mid] = to_string(root->val);
        
        if(root->left)
            printBT(res, root->left, h + 1, begin, mid - 1);
        if(root->right)
            printBT(res, root->right, h + 1, mid + 1, end);
        return;
    }
    //calculate the depth of tree
    int depthOfTree(TreeNode * root)
    {
        if(!root)
            return 0;
        return 1 + max(depthOfTree(root->left), depthOfTree(root->right));
    }
    //
    
};

二、

111. Minimum 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.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its minimum depth = 2.

解答:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int minDepth(TreeNode* root) {
        //方法一:递归法
//         if(!root)
//             return 0;
//         if(!root->left && !root->right)
//             return 1;//1表示本身的节点
//         if(!root->left) 
//             return minDepth(root->right) + 1;//1表示本身的节点
//         if(!root->right)
//             return minDepth(root->left) + 1;
        
//         return 1 + min(minDepth(root->left), minDepth(root->right));//1表示本身的节点
        //方法二:利用层序遍历的思想 栈
        if(!root)
            return 0;
        queue<TreeNode*> q;
        q.push(root);
        
        int level = 0;
        while(!q.empty())
        {
            
            
            ++level;
            int n = q.size();
            for(int i = 0; i < n; ++i)
            {
                TreeNode* p = q.front();
                q.pop();
                
                if(p->left == nullptr && p ->right == nullptr)//均满足则是找到了树最小的路径,return level
                {
                    return level;
                    
                }
                
                if(p->left)
                    q.push(p->left);
                if(p->right)
                    q.push(p->right);
            }
            
            
        
        }
        return level;
        
        
    }
};

三、

题目:

104. Maximum 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.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its depth = 3.

解答:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(!root)
            return 0;
        return 1 + max(maxDepth(root->left), maxDepth(root->right));
    }
};

四、

题目:

637. Average of Levels in Binary Tree


Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.

Example 1:

Input:
    3
   / \
  9  20
    /  \
   15   7
Output: [3, 14.5, 11]
Explanation:
The average value of nodes on level 0 is 3,  on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].

Note:

  1. The range of node's value is in the range of 32-bit signed integer.

解答:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<double> averageOfLevels(TreeNode* root) {
        if(!root)
            return res;
        queue<TreeNode*> q;
        q.push(root);
        q.push(nullptr);
        while(!q.empty())
        {
            TreeNode* p = q.front();
            q.pop();
            
            if(p == nullptr)
            {
                double cur_average = cur_sum / cnt;
                res.push_back(cur_average);
                cur_sum = 0;
                cnt = 0;
                if(q.size() > 0)
                    q.push(nullptr);
            }
            else
            {
                cur_sum += p->val;
                ++cnt;
                
                if(p->left)
                    q.push(p->left);
                if(p->right)
                    q.push(p->right);
            }
        }
        return res;
    }
private:
    vector<double> res;
    double cur_sum = 0;
    int cnt = 0;
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值