/** * 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); }};