Populating Next Right Pointers in Each Node I & II

Populating Next Right Pointers in Each Node

  Total Accepted: 10797  Total Submissions: 31598 My Submissions

Given a binary tree

    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


Populating Next Right Pointers in Each Node II

  Total Accepted: 7484  Total Submissions: 25621 My Submissions

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:

  • You may only use constant extra space.

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
乍看到第一题的时候没想起来怎么做,常量空间对于递归结构来说太不自然了,之后慢慢硬琢磨出来一点想法,以一种很复杂的方法把第一题做了,又看了看第二题,又愣了,慢慢琢磨了一个方法,倒腾了好久,做出来了.但是这一大坨代码,怎么看也不像一个正常的解,去网上看了看,果然自己智商不够啊...

I.考虑到要求常量空间,我琢磨了半天,想到可以将每一个结点的next变量当作栈来模拟递归,代码如下,做了第二题以后,发现其实可以从左往右递归会更简练一点.

II(1)延续第一题的思路利用next变量,不过这次更麻烦,通过从root到leaf每一层设一个前沿指针,并把它们链接起来,自下而上推进前沿并维持前沿链.这中间情况比较复杂...

II(2)网上找的方法,一层层构建,第一层不用构建,当n-1层构建好时,走过n-1层构建第n层,over...

class Solution {
private:
	TreeLinkNode *findNext(TreeLinkNode *what)//找到what结点的右边 
	{
		int c = 0;
		while(what->next != NULL && what == what->next->right)
		{
			what = what->next;
			c++;
		}
		if(what->next == NULL)
		{
			return NULL;
		}
		what = what->next->right;
		while(c-- > 0)
		{
			what = what->left;
		}
		return what;
	}
public:
    void connect(TreeLinkNode *root) {
        if(root == NULL)
        {
        	return;
        }
        if(root->left == NULL)
    	{
    		root->next = NULL;
    		return;
    	}
        root->next = NULL;
        TreeLinkNode xxx(0);//哨兵,最右边的一条root to leaf每个结点的next值为NULL,但同时循环中用NULL判断是否来过
        TreeLinkNode *what = root;
        while(what != NULL)
        {
        	if(what->left == NULL || what->left->next != NULL)//叶结点或子结点已走过 
        	{
        		TreeLinkNode *parent = what->next;
        		if(what == parent->left)//当前结点是亲结点的左孩子 
        		{
        			what->next = parent->right;
        		}
        		else
        		{
        			what->next = findNext(what);
        			if(what->next == NULL)
        			{
        				what->next = &xxx;
        			}
        		}
        		if(what == root->left)//Over. 
        		{
        			break;
        		}
        		else
        		{
        			what = parent;
        		}
        	}
        	else if(what->right->next == NULL)//进入右子树 
        	{
        		what->right->next = what;
        		what = what->right;
        	}
        	else//进入左子树 
        	{
        		what->left->next = what;
        		what = what->left;
        	}
        }
        what = root->right;//还原哨兵值 
        while(what != NULL)
        {
        	what->next = NULL;
        	what = what->right;
        }
	}
};

class Solution {
private:
	void build(TreeLinkNode *root)//建立层级链 
	{
		while(root->left != NULL)
		{
			root->next = root->left;
			root = root->next;
		}
	}
	TreeLinkNode *go(TreeLinkNode *root)//寻找当前链中离底部最近的可拓展结点(右子树为空) 
	{
		TreeLinkNode *last = NULL;
		while(root != NULL)
		{
			if(root->next != root->right && root->right != NULL)
			{
				last = root;
			}
			root = root->next;
		}
		return last;
	}
	TreeLinkNode *getChild(TreeLinkNode *root)//抓取子结点,左优先 
	{
		if(root->left != NULL)
		{
			return root->left;
		}
		else
		{
			return root->right;
		}
	}
public:
    void connect(TreeLinkNode *root) {
        if(root == NULL)
        {
        	return;
        }
        TreeLinkNode *level;
        build(root);
		while((level = go(root)) != NULL)
		{	
			TreeLinkNode *t = level->next;
			if(t == NULL)//链长增加,更新 
			{
				level->next = level->right;
				level = level->next;
				while(level->left != NULL)
				{
					level->next = level->left;
					level = level->next;
				}
			}
			else//右子树拓展 
			{
				level->next = level->right;
				level->right->next = t->next;
				t->next = level->right;
				
				level = level->right;
				TreeLinkNode *c;
				while((c = getChild(level)) != NULL)
				{
					t = level->next;
					level->next = c;
					if(t != NULL)
					{
						c->next = t->next;
						t->next = c;
					}
					level = level->next;
				}
			}
		}
		//对尾部指针封零 
		while(root->next != NULL)
		{
			TreeLinkNode *t = root;
			root = root->next;
			t->next = NULL;
		}
	}
};

class Solution {
public:
    void connect(TreeLinkNode *root) {
        if(root == NULL)
        {
        	return;
        }
		TreeLinkNode *nextLH = root;
		while(nextLH != NULL)
		{
			TreeLinkNode *nowLN = nextLH;
			TreeLinkNode *tail = NULL;
			nextLH = NULL;
			while(nowLN != NULL && nowLN->left == NULL && nowLN->right == NULL)//寻找下一级的头结点 
			{
				nowLN = nowLN->next;
			}
			if(nowLN != NULL)
			{
				if(nowLN->left != NULL)
				{
					nextLH = nowLN->left;
					nextLH->next = nowLN->right;
					tail = nextLH->next == NULL ? nextLH : nextLH->next;
				}
				else
				{
					nextLH = tail = nowLN->right;
				}
			}
			nowLN = nowLN == NULL ? nowLN : nowLN->next;
			while(nowLN != NULL)//通过本级链接下一级 
			{
				if(nowLN->left != NULL)
				{
					tail->next = nowLN->left;
					tail = tail->next;
				}
				if(nowLN->right != NULL)
				{
					tail->next = nowLN->right;
					tail = tail->next;
				}
				nowLN = nowLN->next;
			}
		}
	}
};



1. Two Sum 2. Add Two Numbers 3. Longest Substring Without Repeating Characters 4. Median of Two Sorted Arrays 5. Longest Palindromic Substring 6. ZigZag Conversion 7. Reverse Integer 8. String to Integer (atoi) 9. Palindrome Number 10. Regular Expression Matching 11. Container With Most Water 12. Integer to Roman 13. Roman to Integer 14. Longest Common Prefix 15. 3Sum 16. 3Sum Closest 17. Letter Combinations of a Phone Number 18. 4Sum 19. Remove Nth Node From End of List 20. Valid Parentheses 21. Merge Two Sorted Lists 22. Generate Parentheses 23. Swap Nodes in Pairs 24. Reverse Nodes in k-Group 25. Remove Duplicates from Sorted Array 26. Remove Element 27. Implement strStr() 28. Divide Two Integers 29. Substring with Concatenation of All Words 30. Next Permutation 31. Longest Valid Parentheses 32. Search in Rotated Sorted Array 33. Search for a Range 34. Find First and Last Position of Element in Sorted Array 35. Valid Sudoku 36. Sudoku Solver 37. Count and Say 38. Combination Sum 39. Combination Sum II 40. First Missing Positive 41. Trapping Rain Water 42. Jump Game 43. Merge Intervals 44. Insert Interval 45. Unique Paths 46. Minimum Path Sum 47. Climbing Stairs 48. Permutations 49. Permutations II 50. Rotate Image 51. Group Anagrams 52. Pow(x, n) 53. Maximum Subarray 54. Spiral Matrix 55. Jump Game II 56. Merge k Sorted Lists 57. Insertion Sort List 58. Sort List 59. Largest Rectangle in Histogram 60. Valid Number 61. Word Search 62. Minimum Window Substring 63. Unique Binary Search Trees 64. Unique Binary Search Trees II 65. Interleaving String 66. Maximum Product Subarray 67. Binary Tree Inorder Traversal 68. Binary Tree Preorder Traversal 69. Binary Tree Postorder Traversal 70. Flatten Binary Tree to Linked List 71. Construct Binary Tree from Preorder and Inorder Traversal 72. Construct Binary Tree from Inorder and Postorder Traversal 73. Binary Tree Level Order Traversal 74. Binary Tree Zigzag Level Order Traversal 75. Convert Sorted Array to Binary Search Tree 76. Convert Sorted List to Binary Search Tree 77. Recover Binary Search Tree 78. Sum Root to Leaf Numbers 79. Path Sum 80. Path Sum II 81. Binary Tree Maximum Path Sum 82. Populating Next Right Pointers in Each Node 83. Populating Next Right Pointers in Each Node II 84. Reverse Linked List 85. Reverse Linked List II 86. Partition List 87. Rotate List 88. Remove Duplicates from Sorted List 89. Remove Duplicates from Sorted List II 90. Intersection of Two Linked Lists 91. Linked List Cycle 92. Linked List Cycle II 93. Reorder List 94. Binary Tree Upside Down 95. Binary Tree Right Side View 96. Palindrome Linked List 97. Convert Binary Search Tree to Sorted Doubly Linked List 98. Lowest Common Ancestor of a Binary Tree 99. Lowest Common Ancestor of a Binary Search Tree 100. Binary Tree Level Order Traversal II
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值