LeetCode--Binary Tree Level Order Traversal

6000 단어 LeetCode

Binary Tree Level Order Traversal


이 몇 개의 제목은 유사한데 모두 같은 귀속법으로 시간 공간의 복잡도는 모두 O(n)이다.
물론 교체법도 있습니다. 컨트롤의 복잡도는 O(1)로 내려가므로 이것은 잠시 토론하지 않겠습니다.

Binary Tree Level Order Traversal

//  ,  O(n),  O(n) class Solution {
public:
      vector<vector<int> > levelOrder(TreeNode *root) {
          vector<vector<int>> result;
          traverse(root, 1, result);
          return result;
}
      void traverse(TreeNode *root, size_t level, vector<vector<int>> &result) {
          if (!root) return;
          if (level > result.size())
              result.push_back(vector<int>());
          result[level-1].push_back(root->val);
          traverse(root->left, level+1, result);
          traverse(root->right, level+1, result);
} };

Binary Tree Level Order Traversal II

//  ,  O(n),  O(n)
class Solution {
public:
vector<vector<int> > levelOrderBottom(TreeNode *root) { vector<vector<int>> result;
traverse(root, 1, result);
std::reverse(result.begin(), result.end()); //   return result;
}
      void traverse(TreeNode *root, size_t level, vector<vector<int>> &result) {
          if (!root) return;
          if (level > result.size())
              result.push_back(vector<int>());
          result[level-1].push_back(root->val);
          traverse(root->left, level+1, result);
          traverse(root->right, level+1, result);
} };

Binary Tree Zigzag Level Order Traversal

//  ,  O(n),  O(n)
class Solution {
public:
      vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
          vector<vector<int>> result;
          traverse(root, 1, result, true);
          return result;
}
      void traverse(TreeNode *root, size_t level, vector<vector<int>> &result,
              bool left_to_right) {
          if (!root) return;
          if (level > result.size())
              result.push_back(vector<int>());
          if (left_to_right)
              result[level-1].push_back(root->val);
          else
              result[level-1].insert(result[level-1].begin(), root->val);
          traverse(root->left, level+1, result, !left_to_right);
          traverse(root->right, level+1, result, !left_to_right);
      }
};

좋은 웹페이지 즐겨찾기