力扣算法题—145BinartTreePostorderTraversal

Given a binary tree, return the postorder traversal of its nodes' values.

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [3,2,1]

Follow up: Recursive solution is trivial, could you do it iteratively?

Solution:

  使用两个栈,来实现;

  使用一个栈来实现

  

 1 class Solution {
 2 public:
 3     ListNode* sortList(ListNode* head) {
 4         if (head == nullptr || head->next == nullptr)return head;
 5         ListNode *slow = head, *fast = head, *pre = head;
 6         while (fast != nullptr && fast->next != nullptr)
 7         {
 8             pre = slow;
 9             slow = slow->next;
10             fast = fast->next->next;
11         }
12         pre->next = nullptr;//将链表分为两段
13         return merge(sortList(head), sortList(slow));
14     }
15     ListNode* merge0(ListNode* l1, ListNode* l2)
16     {
17         if (l1 == nullptr || l2 == nullptr)return l1 == nullptr ? l2 : l1;
18         if (l1->val < l2->val)
19         {
20             l1->next = merge(l1->next, l2);
21             return l1;
22         }
23         else
24         {
25             l2->next = merge(l1, l2->next);
26             return l2;
27         }
28     }
29     ListNode* merge(ListNode* l1, ListNode* l2)
30     {
31         ListNode* ptr = new ListNode(-1);
32         ListNode* p = ptr;
33         while (l1 != nullptr && l2 != nullptr)
34         {
35             if (l1->val < l2->val)
36             {
37                 p->next = l1;
38                 l1 = l1->next;
39             }
40             else
41             {
42                 p->next = l2;
43                 l2 = l2->next;
44             }
45             p = p->next;
46         }
47         if (l1 == nullptr)p->next = l2;
48         if (l2 == nullptr)p->next = l1;
49         return ptr->next;
50     }
51 };

猜你喜欢

转载自www.cnblogs.com/zzw1024/p/11774551.html