897. Increasing Order Search Tree(python+cpp)
阿新 • • 發佈:2018-11-09
題目:
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);
}
};
總結:
剛開始看覺得好難啊,看不懂別人的思路程式碼,後來發現,霧草???這不就是一個批了羊皮的中序遍歷嘛??????