带父节点的二叉树的后序遍历 不使用递归和stack

#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>

using namespace std;

class ListNode{
public:
    ListNode(int k):val(k){
        left = NULL;
        right = NULL;
        father = NULL;
    }
    ListNode* left;
    ListNode* right;
    ListNode* father;
    int val;
};

void back(ListNode* root)
{
    if (!root)
        return;
    
    ListNode* last = NULL;
    ListNode* now = root;
    while (now)
    {
        if (last == now->left)
        {
            if (now->right)
            {
                now = now->right;
            }
            else
            {
                cout<<now->val<<" ";
                last = now;
                
                now = now->father;
                continue;
            }
        }
        else if (last == now->right)
        {
            cout<<now->val<<" ";
            last = now;
            
            now = now->father;
            continue;
        }
   
        while (now->left)
            now = now->left;
        
        cout<<now->val<<" ";
        last = now;
        
        now = now->father;
    }
}

int main(int argc, char *argv[])
{
    ListNode a1(1);
    ListNode a2(2);
    ListNode a3(3);
    ListNode a4(4);
    ListNode a5(5);
    ListNode a6(6);
    ListNode a7(7);
    
    a1.left = &a2;
    a1.right = &a3;
    a2.father = &a1;
    a3.father = &a1;
    a2.left = &a4;
    a2.right = &a5;
    a3.left = &a6;
    a3.right = &a7;
    a4.father = &a2;
    a5.father = &a2;
    a6.father = &a3;
    a7.father = &a3;
    back(&a1);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值