C++_学习随笔_重构二叉树和判断是否是对称二叉树
通过输入二叉树的前序遍历和中序遍历重构二叉树,
然后对二叉树进行是否是对称二叉树的判断。
1 #include<iostream> 2 #include<vector> 3 using namespace std; 4 5 struct TreeNode { 6 int val; 7 TreeNode* left; 8 TreeNode* right; 9 TreeNode(int x):val(x),left(NULL),right(NULL){} 10 }; 11 12 //根据前序遍历和中序遍历重构二叉树 13 TreeNode* reConstructBinaryTree(vector<int>pre, vector<int>vin) { 14 if (pre.empty() || vin.empty()) 15 return nullptr; 16 //根节点 17 TreeNode *root = new TreeNode(pre[0]); 18 int root_index = 0; 19 //找到根节点的索引值 20 for (int i = 0; i < pre.size(); i++) { 21 if (vin[i] == pre[0]) { 22 root_index = i; 23 break; 24 } 25 } 26 vector<int> pre_left, pre_right, vin_left, vin_right; 27 for (int i = 0; i < root_index; i++) { 28 pre_left.push_back(pre[i + 1]); 29 vin_left.push_back(vin[i]); 30 } 31 32 for (int i = root_index + 1; i < pre.size(); i++) { 33 pre_right.push_back(pre[i]); 34 vin_right.push_back(vin[i]); 35 } 36 37 root->left = reConstructBinaryTree(pre_left, vin_left); 38 root->right = reConstructBinaryTree(pre_right, vin_right); 39 40 return root; 41 } 42 43 44 //判断是否是对称的 45 bool isSymmetrical(TreeNode* p1, TreeNode* p2) { 46 if (p1 == NULL && p2 == NULL) 47 return true; 48 if (p1 == NULL || p2 == NULL) 49 return false; 50 if (p1->val != p2->val) 51 return false; 52 return isSymmetrical(p1->left, p2->right) && isSymmetrical(p1->right, p2->left); 53 } 54 55 56 bool isSymmetrical(TreeNode* pRoot) { 57 if (pRoot == NULL) { 58 return true; 59 } 60 return isSymmetrical(pRoot, pRoot); 61 } 62 63 64 int main() { 65 vector<int> pre, vin; 66 cout << "请输入节点数:"<<endl; 67 int n = 0,temp; 68 cin >> n; 69 cout << "请输入前序遍历:" << endl; 70 for (int i = 0; i < n; i++) { 71 cin >> temp; 72 pre.push_back(temp); 73 } 74 cout << "请输入中序遍历:" << endl; 75 for (int i = 0; i < n; i++) { 76 cin >> temp; 77 vin.push_back(temp); 78 } 79 bool is; 80 TreeNode* root_node = reConstructBinaryTree(pre, vin); 81 is = isSymmetrical(root_node); 82 cout << is; 83 84 }
8
6 6
5 7 7 5
8
6 9
5 7 7 5
参考链接:
https://www.cnblogs.com/wanglei5205/p/8503036.html
https://cuijiahua.com/blog/2018/01/basis_58.html