当前位置:   article > 正文

C语言 | Leetcode C++题解之第199题二叉树的右视图

C语言 | Leetcode C++题解之第199题二叉树的右视图

题目:

题解:

  1. #define MAX_NODE_NUM 100
  2. int* rightSideView(struct TreeNode* root, int* returnSize){
  3. if (root == NULL) {
  4. *returnSize = 0;
  5. return NULL;
  6. }
  7. int *res = (int *)malloc(sizeof(int) * MAX_NODE_NUM);
  8. int cnt = 0;
  9. struct TreeNode **record = (struct TreeNode **)malloc(sizeof(struct TreeNode *) * MAX_NODE_NUM);
  10. int head = 1;
  11. int tail = 0;
  12. record[0] = root;
  13. while (head > tail) {
  14. int turn = head - tail;
  15. for (int i = 0; i < turn; i++) {
  16. struct TreeNode *cur = record[tail + i];
  17. if (cur->left != NULL) {
  18. record[head++] = cur->left;
  19. }
  20. if (cur->right != NULL) {
  21. record[head++] = cur->right;
  22. }
  23. if (i == turn - 1) {
  24. res[cnt++] = cur->val;
  25. }
  26. }
  27. tail += turn;
  28. }
  29. *returnSize = cnt;
  30. return res;
  31. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/773361
推荐阅读
相关标签
  

闽ICP备14008679号