首页 > 其他 > 详细

Populating Next Right Pointers in Each Node

时间:2015-03-24 22:53:27      阅读:312      评论:0      收藏:0      [点我收藏+]
/**
 * 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) {}
 * };
 */
 /*
 给二叉树的每个节点加一个Next指针,使得每个节点指向它的相连节点,如果该指针没有相连节点next就指向NULL
 暴力写了一下,也过了
 */
class Solution {
public:
    void dfs(TreeLinkNode *root1,TreeLinkNode *root2){
        if(!root1||!root2||root1->next!=NULL) return;
        root1->next = root2;
        dfs(root1->left,root1->right);
        dfs(root1->right,root2->left);
        dfs(root2->left,root2->right);
        dfs(root2->right,root2->next);
    }
    void connect(TreeLinkNode *root) {
        if(!root) return ;
        root->next = NULL;
        dfs(root->left,root->right);
        dfs(root->right,root->next);
    }
};

 

/**
 * 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 dfs(TreeLinkNode *root){
        if(!root||!root->left) return;
        root->left->next = root->right;
        root->right->next = (root->next)?root->next->left:NULL;
        dfs(root->left);
        dfs(root->right);
    }
    void connect(TreeLinkNode *root) {
        dfs(root);
    }
};

 

Populating Next Right Pointers in Each Node

原文:http://www.cnblogs.com/llei1573/p/4363995.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!