inorder traversal
vector<int> v;
void inorder(TreeNode* root,vector<int> &v)
{
if(root==NULL)
return;
inorder(root->left,v);
v.push_back(root->val);
inorder(root->right,v);
}
inorder traversal
vector<int> v;
void inorder(TreeNode* root,vector<int> &v)
{
if(root==NULL)
return;
inorder(root->left,v);
v.push_back(root->val);
inorder(root->right,v);
}
inorder traversal
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
return dfs(root, list);
}
private List<Integer> dfs(TreeNode root, List<Integer> list)
{
if(root == null)
return list;
list = dfs(root.left, list);
list.add(root.val);
return dfs(root.right,list);
}
}
preorder traversal
#include <iostream>
using namespace std;
class node{
public:
int data;
node* left;
node* right;
node(int d){
data = d;
left = NULL;
right = NULL;
}
};
node* buildTree(){
int d;
cin>>d;
if(d==-1){
return NULL; //to attach a NULL pointer[in case of no child] enter -1
}
node * root = new node(d);
root->left = buildTree();
root->right = buildTree();
return root;
}
//REQUIRED FUNCTION: Inorder Traversal
void printIn(node*root){
if(root==NULL){
return;
}
//Otherwise Left Root Right
printIn(root->left);
cout<<root->data<<" ";
printIn(root->right);
}
int main(){
node* root = buildTree();
printIn(root);
return 0;
}
//SAMPLE INPUT TO RUN THE CODE ON ANY ONLINE IDE:
//8 10 1 -1 -1 6 9 -1 -1 7 -1 -1 3 -1 14 13 -1 -1 -1
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us