Home  >  Article  >  Java  >  Inorder traversal of a binary tree

Inorder traversal of a binary tree

Linda Hamilton
Linda HamiltonOriginal
2024-09-26 17:31:03158browse

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);
    }
}

The above is the detailed content of Inorder traversal of a binary tree. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn