DEV Community

Prashant Mishra
Prashant Mishra

Posted on

Inorder traversal of a binary tree

Problem

In inorder traversal of a binary tree, we visit left node then root and finally the right node.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        inorder(root,list);
        return list;
    }
    public void inorder(TreeNode node, List<Integer> list){
        if(node ==null) return;

        inorder(node.left,list);
        list.add(node.val);
        inorder(node.right,list);
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)