zoukankan      html  css  js  c++  java
  • 深度优先算法之打印二叉树叶子节点路径

    比如这样一棵二叉树,如何打印二叉树叶子节点路径呢?

    代码如下:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    int result[100] = {0};
    int count = 0;
    
    struct TreeNode {
        int val;
        struct TreeNode *left;
        struct TreeNode *right;
    };
    
    void printNode()
    {
        int i = 0;
        printf("%d", result[i]);
        for(i = 1; i < count; i++) {
            printf("--->%d", result[i]);
        }
        printf("
    ");
    }
    
    void dfs(struct TreeNode* node)
    {
         if(node == NULL) {
            return;
        }
        result[count++] = node->val;
        if (node->right == NULL && node->left == NULL) {
            printNode();
            count--;  //重点在这里回退
            return;
        }
        dfs(node->left);
        dfs(node->right);
        count--;   //重点在这里,要回退
    }
    
    int main() 
    {
        struct TreeNode Node[5];
        Node[0].val = 4;
        Node[0].left = &Node[1];
        Node[0].right = &Node[2];
        Node[1].val = 9;
        Node[1].left = &Node[3];
        Node[1].right = &Node[4];
        Node[2].val = 0;
        Node[2].left = NULL;
        Node[2].right = NULL;
        Node[3].val = 5;
        Node[3].left = NULL;
        Node[3].right = NULL;
        Node[4].val = 1;
        Node[4].left = NULL;
        Node[4].right = NULL;
        dfs(&Node[0]);
        return 0;
    }

    结果:

    当值未一旬,而视茫茫,而发苍苍,而齿牙动摇
  • 相关阅读:
    logging模块、sys模块、shelve模块
    re模块、hashlib模块
    包、常用模块
    模块
    迭代器、生成器、递归、二分法
    函数对象、函数嵌套、名称空间与作用域、闭包函数、装饰器
    函数
    文件处理
    字符编码
    Djiango导读
  • 原文地址:https://www.cnblogs.com/niuniuc/p/14006142.html
Copyright © 2011-2022 走看看