1. 程式人生 > >#Leetcode# 102. Binary Tree Level Order Traversal

#Leetcode# 102. Binary Tree Level Order Traversal

https://leetcode.com/problems/binary-tree-level-order-traversal/

 

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

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

    3
   / \
  9  20
    /  \
   15   7

 

return its level order traversal as:

[
  [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) {
        vector<vector<int> > ans;
        if(!root) return ans;
        helper(root, ans, 1);
        return ans;
    }
    void helper(TreeNode* root, vector<vector<int> >& ans, int depth) {
        vector<int> v;
        if(depth > ans.size()) {
            ans.push_back(v);
            v.clear();
        }
        ans[depth - 1].push_back(root -> val);
        if(root -> left) 
            helper(root -> left, ans, depth + 1);
        if(root -> right)
            helper(root -> right, ans, depth + 1);
    }
};

  

很幸福的時間了