标签:
struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Note:
You may only use constant extra space.
You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
For example,
Given the following perfect binary tree,
1
/ \
2 3
/ \ / \
4 5 6 7
After calling your function, the tree should look like:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ / \
4->5->6->7 -> NULL
注意是完美二叉树,所以
(1)根据题述:左孩子为空,则右孩子一定为空,所以左孩子为空,则return
(2)如果左孩子不为空,则右孩子一定不为空,所以链接左孩子和右孩子即可(左孩子的next赋值为右孩子)
C++:
1 class Solution { 2 public: 3 void connect(TreeLinkNode *root) { 4 5 if(root==NULL) return ; 6 7 if(root->left&&root->right) 8 { 9 root->left->next=root->right; 10 if(root->next) 11 root->right->next=root->next->left; 12 else 13 root->right->next=NULL; 14 } 15 16 connect(root->left); 17 connect(root->right); 18 19 20 } 21 };
Python:
1 # Definition for binary tree with next pointer. 2 # class TreeLinkNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 # self.next = None 8 9 class Solution: 10 # @param root, a tree link node 11 # @return nothing 12 def connect(self, root): 13 if root is None:return 14 if root.left and root.right: 15 root.left.next=root.right 16 if root.next: 17 root.right.next=root.next.left 18 else: 19 root.right.next=None 20 self.connect(root.left) 21 self.connect(root.right)
【leetcode】Populating Next Right Pointers in Each Node
标签:
原文地址:http://www.cnblogs.com/jawiezhu/p/4413183.html