[LeetCode] Find Leaves of Binary Tree 找二叉树的叶节点

Given a binary tree, find all leaves and then remove those leaves. Then repeat the previous steps until the tree is empty.

Example:
Given binary tree

          1
         /         2   3
       / \
      4   5

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

Explanation:

1. Remove the leaves [4, 5, 3] from the tree

          1
         /
        2

2. Remove the leaf [2] from the tree

          1

3. Remove the leaf [1] from the tree

          []

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

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

这道题给了我们一个二叉树,让我们返回其每层的叶节点,就像剥洋葱一样,将这个二叉树一层一层剥掉,最后一个剥掉根节点。那么题目中提示说要用DFS来做,思路是这样的,每一个节点从左子节点和右子节点分开走可以得到两个深度,由于成为叶节点的条件是左右子节点都为空,所以我们取左右子节点中较大值加1为当前节点的深度值,知道了深度值就可以将节点值加入到结果res中的正确位置了,求深度的方法我们可以参见Maximum Depth of Binary Tree中求最大深度的方法,参见代码如下:

解法一:

class Solution {
public:
    vector<vector<int>> findLeaves(TreeNode* root) {
        vector<vector<int>> res;
        helper(root, res);
        return res;
    }
    int helper(TreeNode *root, vector<vector<int>> &res) {
        if (!root) return -1;
        int depth = 1 + max(helper(root->left, res), helper(root->right, res));
        if (depth >= res.size()) res.resize(depth + 1);
        res[depth].push_back(root->val);
        return depth;
    }
};

下面这种DFS方法没有用计算深度的方法,而是使用了一层层剥离的方法,思路是遍历二叉树,找到叶节点,将其赋值为NULL,然后加入leaves数组中,这样一层层剥洋葱般的就可以得到最终结果了:

解法二:

class Solution {
public:
    vector<vector<int>> findLeaves(TreeNode* root) {
        vector<vector<int>> res;
        while (root) {
            vector<int> leaves;
            root = remove(root, leaves);
            res.push_back(leaves);
        }
        return res;
    }
    TreeNode* remove(TreeNode *node, vector<int> &leaves) {
        if (!node) return NULL;
        if (!node->left && !node->right) {
            leaves.push_back(node->val);
            return NULL;
        }
        node->left = remove(node->left, leaves);
        node->right = remove(node->right, leaves);
        return node;
    }
};

类似题目:

Maximum Depth of Binary Tree

Minimum Height Trees

参考资料:

https://leetcode.com/discuss/110406/simple-java-recursive-1ms-solution

https://leetcode.com/discuss/110389/12-lines-simple-java-solution-using-recursion

LeetCode All in One 题目讲解汇总(持续更新中...)

时间: 2024-10-03 21:41:33

[LeetCode] Find Leaves of Binary Tree 找二叉树的叶节点的相关文章

Find Leaves of Binary Tree 找二叉树的叶节点

Given a binary tree, find all leaves and then remove those leaves. Then repeat the previous steps until the tree is empty. Example:Given binary tree 1 / \ 2 3 / \ 4 5 Returns [4, 5, 3], [2], [1]. Explanation:1. Remove the leaves [4, 5, 3] from the tr

LeetCode 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

LeetCode 543. Diameter of Binary Tree (二叉树的直径)

Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longestpath between any two nodes in a tree. This path may or may not pass through the root. Example:Given a binary tr

LeetCode Minimum Depth of Binary Tree 找最小深度(返回最小深度)

题意:找到离根结点最近的叶子结点的那一层(设同一层上的结点与根结点的距离相等),返回它所在的层数. 方法有: 1.递归深度搜索 2.层次搜索 方法一:递归(无优化) 1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL)

leetcode题解:Construct Binary Tree from Inorder and Postorder Traversal(根据中序和后序遍历构造二叉树)

题目: Given inorder and postorder traversal of a tree, construct the binary tree. Note:You may assume that duplicates do not exist in the tree. 说明: 1)实现与根据先序和中序遍历构造二叉树相似,题目参考请进 算法思想 中序序列:C.B.E.D.F.A.H.G.J.I 后序序列:C.E.F.D.B.H.J.I.G.A 递归思路: 根据后序遍历的特点,知道后序

[LeetCode] Serialize and Deserialize Binary Tree 二叉树的序列化和去序列化

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another comput

LeetCode——Serialize and Deserialize Binary Tree

Description: Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or a

LeetCode——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. 此题和求二叉树的最短路径几乎一模一样. public int maxDepth(TreeNode root) { if (root == null) return 0; int a

【LeetCode-面试算法经典-Java实现】【111-Minimum Depth of Binary Tree(二叉树的最小深度)】

[111-Minimum Depth of Binary Tree(二叉树的最小深度)] [LeetCode-面试算法经典-Java实现][所有题目目录索引] 原题 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. 题目大意 给定