二叉树搜索

这里写自定义目录标题

#include <iostream>
#include <vector>


using namespace std;

struct Node{
    int value;
    Node* left_node;
    Node* right_node;

    Node(int v){
        value = v;
        left_node = nullptr;
        right_node = nullptr;    
    }
};
 
bool findNode(Node* node, int target_node, vector<int>& path){
    if (!node) return false;

    cout << "---node->value : "<< node->value << endl; 

    // save path
    path.push_back(node->value);
    
    // find target node
    if (node->value == target_node)
    {
         cout << "---find target_node--- "<< endl;   
        return true;
    }

    // cout << "---2--- "<< endl;    

    // 如果左分支或者右分支找到了
    if (findNode(node->left_node, target_node, path)){
        return true;
    } 
    if (findNode(node->right_node, target_node, path)){
        return true;
    }

    path.pop_back();

    return false;
}


void findTreePath(Node* root_node, int curr_node ,int goal_node, vector<int>& path){

    // find curr node path 
    vector<int> path1;
    bool ret = findNode(root_node, curr_node, path1);
    cout << "ret: " << ret << endl;

    cout << "path1," << path1.size() << ":";
    for (auto p: path1){
        cout << p << " --> " ;
    }
    cout << endl;


    vector<int> path2;
    // find goal node path 
    findNode(root_node, goal_node, path2);

    cout << "path2" << endl;
    for (auto p: path2){
        cout << p << " --> " ;
    }
    cout << endl;


    // pingjie path
    for (int i = path1.size()-1; i >= 0; i--){
        path.push_back(path1[i]);
    }

    for (int i = 1; i < path2.size(); i++){
        path.push_back(path2[i]);
    }
    

}

int main(){

    Node* root_node  = new Node(4);
    root_node->left_node = new Node(3);
    root_node->right_node = new Node(5);

    root_node->left_node->left_node = new Node(1);
    root_node->left_node->right_node = new Node(2);

    root_node->right_node->left_node = new Node(6);
    root_node->right_node->right_node = new Node(7);

    int curr_node = 1;
    int goal_node = 7;

    vector<int> path;
    findTreePath(root_node, curr_node, goal_node, path);

    cout << "Total path:" << endl;
    for (auto p: path){
        cout << p << " --> " ;
    }
    cout << endl;

    return 0;
}

输出

---node->value : 4
---node->value : 3
---node->value : 1
---find target_node--- 
ret: 1
path1,3:4 --> 3 --> 1 --> 
---node->value : 4
---node->value : 3
---node->value : 1
---node->value : 2
---node->value : 5
---node->value : 6
---node->value : 7
---find target_node--- 
path2
4 --> 5 --> 7 --> 
Total path:
1 --> 3 --> 4 --> 5 --> 7 --> 
 
Normal program termination. Exit status: 0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值