Skip to content

Latest commit

 

History

History
84 lines (70 loc) · 2.08 KB

_94. Binary Tree Inorder Traversal.md

File metadata and controls

84 lines (70 loc) · 2.08 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : June 29, 2024

Last updated : June 29, 2024


Related Topics : Stack, Tree, Depth-First Search, Binary Tree

Acceptance Rate : 78.06 %


Solutions

Java

/**
 * 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) {
        ArrayList<Integer> output = new ArrayList<>();
        helper(root, output);
        return output;
    }

    private void helper(TreeNode curr, ArrayList<Integer> output) {
        if (curr == null) {
            return;
        }
        helper(curr.left, output);
        output.add(curr.val);
        helper(curr.right, output);
    }
}

Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        self.output = []
        def helper(curr: Optional[TreeNode]) -> None :
            if not curr :
                return
            
            helper(curr.left)
            self.output.append(curr.val)
            helper(curr.right)

        helper(root)
        return self.output