117. Populating Next Right Pointers in Each Node II

来源:互联网 发布:淘宝钻石展位怎么样 编辑:程序博客网 时间:2024/06/16 07:00

本来想用DFS实现最后,但是发现了一些我不能解决的测试样例,还是采用了层序遍历这种具有普适性的思路。

/** * Definition for binary tree with next pointer. * struct TreeLinkNode { *  int val; *  TreeLinkNode *left, *right, *next; *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} * }; */class Solution {public:    void connect(TreeLinkNode *root) {        if(root==NULL)            return;        queue<TreeLinkNode *> node;        queue<int> depth;        TreeLinkNode * nowNode=NULL;        int nowDepth=0;        node.push(root);        depth.push(1);        while(!node.empty())        {            if(node.front()->left!=NULL)            {                node.push(node.front()->left);                depth.push(depth.front()+1);            }            if(node.front()->right!=NULL)            {                node.push(node.front()->right);                depth.push(depth.front()+1);            }            if(nowDepth==depth.front())                nowNode->next=node.front();            nowNode=node.front();            nowDepth=depth.front();            node.pop();            depth.pop();        }    }};
0 0
原创粉丝点击