标签:
Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
For example,
Given the following binary tree,
1 / 2 3 / \ 4 5 7
After calling your function, the tree should look like:
1 -> NULL / 2 -> 3 -> NULL / \ 4-> 5 -> 7 -> NULL
解题思路:
同 leetcode-Populating Next Right Pointers in Each Node,见http://blog.csdn.net/sinat_24520925/article/details/45624409,不同的是,二叉树不一定是完全二叉树,可以是不完全的二叉树。这样一来,按以前的方法复杂度高,且容易出错。其实我们只需要知道每一层的第一个元素head,以及现在所找的节点同层的上一个节点prev,根据每个元素的left、right、以及next。便可遍历本树的所有节点,并给新元素添加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 connect(TreeLinkNode *root) { if(root==NULL) return; root->next=NULL; if(root->left==NULL&root->right==NULL) return; TreeLinkNode *head=NULL;//下一层节点的开头 TreeLinkNode *prev=NULL;//现在所找的节点同层的上一个节点 while(root) { TreeLinkNode *node=root; while(node) { if(node->left) { if(prev!=NULL) prev->next=node->left; else { head=node->left; } prev=node->left; } if(node->right) { if(prev!=NULL) prev->next=node->right; else { head=node->right; } prev=node->right; } node=node->next; } root=head; head=NULL; prev=NULL; } } };
leetcode--Populating Next Right Pointers in Each Node II
标签:
原文地址:http://blog.csdn.net/sinat_24520925/article/details/46126363