https://pintia.cn/problem-sets/994805342720868352/problems/994805440976633856
首先二叉搜索樹是左子樹的元素都小于根,左子樹的元素都大于等于根。
它的鏡像是,左子樹都大于等于根,右子樹都小于根。
#include<bits/stdc++.h>
using namespace std
;
const int N
=1e4+10;
int n
,x
;
int cnt
;
vector
<int>a
,ans
;
struct TreeNode
{int val
;TreeNode
*left
;TreeNode
*right
;TreeNode(int x
) : val(x
), left(NULL), right(NULL) {}
};
TreeNode
* build1(int startx
,int l
,int r
)
{auto root
=new TreeNode(a
[startx
]); cnt
++;int i
; for(i
=startx
+1;i
<n
&&a
[i
]>=l
&&a
[i
]<r
&&a
[i
]<a
[startx
];i
++);if(i
!=startx
+1) root
->left
=build1(startx
+1,l
,a
[startx
]);if(i
<n
&&a
[i
]<r
&&a
[i
]>=a
[startx
]) root
->right
=build1(i
,a
[startx
],r
);return root
;
}
TreeNode
* build2(int startx
,int l
,int r
)
{auto root
=new TreeNode(a
[startx
]); cnt
++;int i
; for(i
=startx
+1;i
<n
&&a
[i
]<r
&&a
[i
]>=a
[startx
];i
++);if(i
!=startx
+1) root
->left
=build2(startx
+1,a
[startx
],r
);if(i
<n
&&a
[i
]<a
[startx
]&&a
[i
]>=l
) root
->right
=build2(i
,l
,a
[startx
]);return root
;
}
void dfs(TreeNode
*root
)
{if(root
->left
) dfs(root
->left
);if(root
->right
) dfs(root
->right
);ans
.push_back(root
->val
);
}
int main(void)
{cin
>>n
;for(int i
=0;i
<n
;i
++) cin
>>x
,a
.push_back(x
);auto root
=build1(0,-1e9,1e9);if(cnt
==n
) {puts("YES");dfs(root
);for(int i
=0;i
<ans
.size();i
++) {if(i
) cout
<<" ";cout
<<ans
[i
];}}else {cnt
=0;auto root
=build2(0,-1e9,1e9);if(cnt
==n
){puts("YES");dfs(root
);for(int i
=0;i
<ans
.size();i
++) {if(i
) cout
<<" ";cout
<<ans
[i
];}}else puts("NO");}return 0;
}
總結
以上是生活随笔為你收集整理的1043 Is It a Binary Search Tree (25 分)【难度: 中 / 知识点: 构造二叉搜索树(BST) 】的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。