版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/83866073
题目:
Given a tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only 1 right child.
Example 1: Input:[5,3,6,2,4,null,8,1,null,null,null,7,9] 5 / \ 3 6 / \ \ 2 4 8 / / \ 1 7 9 Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9] 1 \ 2 \ 3 \ 4 \ 5 \ 6 \ 7 \ 8 \ 9
Note:
The number of nodes in the given tree will be between
1
and100
.
Each node will have a unique integer value from0
to1000
.
解释:
就是把原来的树的中序遍历的结果变成一条线。
递归
左孩子变成父节点
父节点变成左孩子的右孩子的右孩子的。。。。的右孩子
最左边的孩子变成了父节点
需要新建一个头结点newRoot,最后返回newRoot->right ,类似于链表中的新建一个空结点,对这个结点操作,最后返回这个结点的next一样。遍历的过程实际上还是中序遍历,每次把遍历到的只加到新的树的当前的结点的右孩子上。
python代码:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def increasingBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
#第一是使用指向树的指针呢,好紧张
newRoot=TreeNode(0)
self.p=newRoot
def InOrder(root):
if root.left:
InOrder(root.left)
self.p.right=TreeNode(root.val)
self.p=self.p.right
if root.right:
InOrder(root.right)
if root:
InOrder(root)
return newRoot.right
c++代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
//全局工作指针,永远指新树的当前结点
TreeNode *p;
TreeNode* increasingBST(TreeNode* root) {
TreeNode * newRoot=new TreeNode(0);
p=newRoot;
if (root)
InOrder(root);
return newRoot->right;
}
void InOrder(TreeNode* root)
{ if(root->left)
InOrder(root->left);
p->right=new TreeNode(root->val);
p=p->right;
if(root->right)
InOrder(root->right);
}
};
总结:
刚开始看觉得好难啊,看不懂别人的思路代码,后来发现,雾草???这不就是一个批了羊皮的中序遍历嘛??????