以下是中序
遍历 二叉树的
递归 算法和
非递归 算法的
实现代码,供您参考:
递归 算法:
非递归 算法void inorder_recursive(TreeNode* root) {if (root) {inorder_recursive(root->left);cout << root->val << " ";inorder_recursive(root->right);}}
:
void inorder_nonrecursive(TreeNode* root) {stack<TreeNode*> stk;TreeNode* curr = root;while (curr || !stk.empty()) {while (curr) {stk.push(curr);curr = curr->left;}curr = stk.top();stk.pop();cout << curr->val << " ";curr = curr->right;}}
请注意,这里的 `TreeNode`
结构体是
二叉树节点的定义,其中包含了节点的值、左子节点和右子节点。如果您需要使用这些代码,请先自行定义 `TreeNode`
结构体。
版权声明:
本文来源网络,所有图片文章版权属于原作者,如有侵权,联系删除。
本文网址:https://www.mushiming.com/mjsbk/8163.html