二叉树遍历

二叉树遍历 1 中序遍历 使用栈 vector<int> inorderTraversal(TreeNode *root) { // using stack vector<int> nodes; stack<TreeNode *> todoStack; while (root || !todoStack.empty()) { while (root) { todoStack.push(root); root = root->left; } root = todoStack.top(); todoStack.pop(); nodes.push_back(root->val); root = root->right; } return nodes; } 递归 void inorder(TreeNode *root, vector<int> &nodes) { if (!root) { return; } inorder(root->left, nodes); nodes.push_back(root->val); inorder(root->right, nodes); } vector<int>