366. Find Leaves of Binary Tree

https://leetcode.com/problems/find-leaves-of-binary-tree/description/

Given a binary tree, collect a tree’s nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty.

Example:

Given binary tree 
          1
         / \
        2   3
       / \     
      4   5    
Returns [4, 5, 3], [2], [1].

Explanation:
1. Removing the leaves [4, 5, 3] would result in this tree:

      1
     / 
    2          

2. Now removing the leaf [2] would result in this tree:

      1          

3. Now removing the leaf [1] would result in the empty tree:

      []         

Returns [4, 5, 3], [2], [1].

Credits:
Special thanks to @elmirap for adding this problem and creating all test cases.

The main idea of ​​the title: Cut the leaf nodes of the binary tree layer by layer, and output them layer by layer.
Step idea: Depth-first traversal of the binary tree (DFS), calculate the height (distance to the leaf) at each node, this height can be used as pruning According to the order of time, the smaller the height, the first to be cut off.
Code:
Pay special attention, when passing vector<vector<int>> resin as a recursive parameter, you must use the reference &, otherwise the modification will only be in the function scope, and will not change the outside.

/**
 * 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<int>> findLeaves(TreeNode* root) {
        vector<vector<int>> res;
        dfs(root, res);
        return res;
    }
    //辅助函数,深度遍历
    int dfs(TreeNode* root, vector<vector<int>>& res) {
        if (!root) return 0;  //空节点,高度为0
        int level = max(dfs(root->left, res), dfs(root->right, res)) + 1;  //每个节点高度为子树的最大高度+1,递归求
        if (level > res.size()) res.push_back(vector<int>());  //每当高度超过res长度时,res扩张
        //res从0开始,而level从1开始
        res[level-1].push_back(root->val);  //每个节点写入
        return level;
    }
};

Guess you like

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