欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

102. 二叉树的层次遍历

程序员文章站 2022-03-03 10:35:35
...

给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。例如:

给定二叉树: [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回其层次遍历结果:

[
  [3],
  [9,20],
  [15,7]
]
/**
 * 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>> levelOrder(TreeNode* root) {
        int depth = getHight(root);
        vector<vector<int>> result(depth);
        if(depth <= 0)
            return result;
        levelOfOrder(root, 0, result);
        return result;
    }
    void levelOfOrder(TreeNode* root, int depth, vector<vector<int>> &result)
    {
        if(root == NULL)
            return ;
        result[depth].push_back(root->val);
        levelOfOrder(root->left, depth + 1, result);
        levelOfOrder(root->right, depth + 1, result);
    }
    int getHight(TreeNode* root)
    {
        if(root == NULL)
            return 0;
        int L = getHight(root->left);
        int R = getHight(root->right);
        return max(L, R) + 1;
    }
};

 

相关标签: LeetCode