二叉树
构建二叉树:
增加节点:
删除节点:
查询节点:
1.先序遍历
/* 递归版前序遍历 */ void Tree::preOrderWithRecursive(ListNode* root) { if (root == nullptr)return; std::cout << root->val << " "; preOrderNoRecursive(root->left); preOrderNoRecursive(root->right); } /* 非递归版前序遍历 */ vector<int> preorderTraversal(TreeNode* root) { vector<int> res; stack<TreeNode*> s; s.push(root); while(!s.empty()) { TreeNode* p = s.top(); s.pop(); if (p == nullptr)continue; res.push_back(p->val); s.push(p->right); s.push(p->left); } return res; }
2. 后序遍历
前序为 root->left->right, 后序为left->right->root
可以将前序改为root->right->left,然后进行一次翻转就是left->right->root
/* 递归版后序遍历 */ void Tree::postOrderWithRecursive(ListNode* root) { if (root == nullptr)return; postOrderNoRecursive(root->left); postOrderNoRecursive(root->right); std::cout << root->val << " "; } /* 非递归版后序遍历 */ vector<int> postorderTraversal(TreeNode* root) { vector<int> res; stack<TreeNode*> s; s.push(root); while(!s.empty()) { root = s.top(); s.pop(); if (root == nullptr)continue; res.push_back(root->val); s.push(root->left); s.push(root->right); } reverse(res.begin(), res.end()); return res; }
3. 中序遍历
/* 递归版中序遍历 */ void Tree::inOrderWithRecursive(ListNode* root) { if (root == nullptr)return; inOrderNoRecursive(root->left); std::cout << root->val << " "; inOrderNoRecursive(root->right); } /* 非递归版中序遍历 */ vector<int> inorderTraversal(TreeNode* root) { vector<int> res; stack<TreeNode*> s; TreeNode* p = root; while(p || !s.empty()) { while(p) { s.push(p); p = p->left; } p = s.top(); s.pop(); res.push_back(p->val); p = p->right; } return res; }