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;
    }

    结果:

    当值未一旬,而视茫茫,而发苍苍,而齿牙动摇
  • 相关阅读:
    字段与表的对应关系
    java初学代码,还不太熟练
    编程学习心得
    ps中经常遇到的问题
    R语言矩阵运算加速
    写代码过程中一些数字推理公式
    EXCEL中常用的函数
    css样式中常见的属性
    R语言的基本矩阵运算
    excel常用的函数
  • 原文地址:https://www.cnblogs.com/niuniuc/p/14006142.html
Copyright © 2011-2022 走看看