深度优先算法之打印二叉树叶子节点路径

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

 

 

 

代码如下:

#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("\n");
}

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

结果:

 

posted @ 2020-11-19 16:03  牛牛码代码  阅读(275)  评论(0编辑  收藏  举报