leetcode 513. Find Bottom Left Tree Value

来源:互联网 发布:淘宝菜鸟驿站 编辑:程序博客网 时间:2024/06/13 16:43

原题:

Given a binary tree, find the leftmost value in the last row of the tree.

Example 1:

Input:    2   / \  1   3Output:1

Example 2: 

Input:        1       / \      2   3     /   / \    4   5   6       /      7Output:7

Note: You may assume the tree (i.e., the given root node) is not NULL.

求最底层最左边的元素

代码如下:

int findBottomLeftValue(struct TreeNode* root) {    int result;    struct deque1    {        struct TreeNode* node;        struct deque1* next;        struct deque1* front;    };    struct deque1* head;    head=(struct deque1*)malloc(sizeof(struct deque1));    head->node=root;    head->next=NULL;    head->front=NULL;    struct deque1* temp1;    struct deque1* temp2;    while(head!=NULL)    {        int flag=0;        temp2=NULL;        while(head!=NULL)        {            if(flag==0)            {                result=head->node->val;                flag=1;            }            if(head->node->left!=NULL)            {                temp1=(struct deque1*)malloc(sizeof(struct deque1));                temp1->node=head->node->left;                temp1->next=temp2;                if(temp2!=NULL)                    temp2->front=temp1;                temp1->front=NULL;                temp2=temp1;            }            if(head->node->right!=NULL)            {                temp1=(struct deque1*)malloc(sizeof(struct deque1));                temp1->node=head->node->right;                temp1->next=temp2;                if(temp2!=NULL)                    temp2->front=temp1;                temp1->front=NULL;                temp2=temp1;            }            struct deque1* p=head;            head=head->front;            free(p);        }        while(temp2!=NULL&&temp2->next!=NULL)        {            temp2=temp2->next;        }        head=temp2;    }    return result;}
其实还是层序遍历。

上一题我偷懒,没有按顺序排序,也写的是单链表。现在只能用双链表了。不然元素顺序会乱。

原创粉丝点击