创建二叉树
- 先序和中序创建树
- #号法创建树
利用前序遍历来创建树 Bintree createBTpre( ) { Bintree T; char ch; scanf(“%c”,&ch); if(ch==’#’) T=NULL; else { T=( Bintree )malloc(sizeof(BinTNode)); T->data=ch; T->lchild=createBTpre(); T->rchild=createBTpre(); } return T; } 利用后序遍历来销毁树 void BiTree_Free(BiTNode* T) { BiTNode *tmp = NULL; if (T!= NULL) { if (T->rchild != NULL) BiTree_Free(T->rchild); if (T->lchild != NULL) BiTree_Free(T->lchild); if (T != NULL) { free(T); T = NULL; } } }
验证对称二叉树
非递归完成
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isSymmetric(TreeNode *root) { if (!root) return true; queue<TreeNode*> q1, q2; q1.push(root->left); q2.push(root->right); while (!q1.empty() && !q2.empty()) { TreeNode *node1 = q1.front(); TreeNode *node2 = q2.front(); q1.pop(); q2.pop(); if((node1 && !node2) || (!node1 && node2)) return false; if (node1) { if (node1->val != node2->val) return false; q1.push(node1->left); q1.push(node1->right); q2.push(node2->right); q2.push(node2->left); } } return true; } };
递归 class Solution { public: bool isSymmetric(TreeNode *root) { if (!root) return true; return isSymmetric(root->left, root->right); } bool isSymmetric(TreeNode *left, TreeNode *right) { if (!left && !right) return true; if (left && !right || !left && right || left->val != right->val) return false; return isSymmetric(left->left, right->right) && isSymmetric(left->right, right->left); } };