public: void inord(TreeNode *root, vector <int> inorder){ if(!root) return; if(root->left) inord(root->left, inorder); inorder.push_back(root->val); if(root->right) inord(root->right, inorder); } vector<int> inorderTraversal(TreeNode* root) { // if(root==NULL) return {}; vector <int> inorder; inord(root, inorder); return inorder; }};
Question
public: void inord(TreeNode root, vector <int> inorder){ if(!root) return; if(root->left) inord(root->left, inorder); inorder.push_back(root->val); if(root->right) inord(root->right, inorder); } vector<int> inorderTraversal(TreeNode root) { // if(root==NULL) return {}; vector <int> inorder; inord(root, inorder); return inorder; }};
Solution
This is a C++ function for an Inorder Traversal of a Binary Tree. Here's a step-by-step explanation:
-
The function
inord(TreeNode *root, vector <int> inorder)is a helper function that performs the actual Inorder Traversal. It takes a pointer to a TreeNode and a reference to a vector of integers as arguments. -
If the root is null, the function returns immediately. This is the base case for the recursion.
-
If the root has a left child, the function calls itself recursively with the left child as the new root.
-
After returning from the left subtree, it adds the value of
Similar Questions
What is wrong with the below code for the inorder traversal of in order threaded binary tree:
- Provide a detailed algorithm for the Inorder tree traversal method. explain the answer for 5 marks
Invert the Binary TreeGiven the root of a binary tree, invert the tree, and return its root. Print the Inorder traversal of the inverted tree.Input format:The input consists of one line, space-separated elements denoting the nodes of the Binary Tree.Output format:Print the inorder traversal of the inverted tree in a single line.
Complete below code of Preorder traversalPreorder(node* root){If(a-----------------){cout<<root->data;b--------------------------;preorder(root->right);}} a.NULL b.root->lefta.root==NULL b.Preorder(root->left);a.root!=NULL b.Preorder(root->left);a.root!=NULL b.root->left
Complete the function in the editor below. It received parameter: a pointer to the root of a binary tree. It must print the values in the tree's postorder traversal as a single line of space-separated values.
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.