Home > Java > javaTutorial > body text

Inorder traversal of a binary tree

Linda Hamilton
Release: 2024-09-26 17:31:03
Original
280 people have browsed it

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);
    }
}
Copy after login

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!

source:dev.to
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!