Friday, July 30, 2021
More

    Binary Tree Inorder Traversal

    Must Read

    Programmerhttp://www.improgrammer.net
    We started this site to inspire young minds to motivate and encourage them towards Programming Language. In this site you will get programming tutorials, tech, programming facts, programming fun and programming blogs.
    Given a binary tree, return the inorder traversal of its nodes’ values.

    For example:
    Given binary tree [1,null,2,3],

       1
        \
         2
        /
       3
    

    return [1,3,2].

    Note: Recursive solution is trivial, could you do it iteratively?


    Solution:
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     * int val;
     * TreeNode left;
     * TreeNode right;
     * TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
    
      List<Integer> list = new ArrayList<Integer>();
      public List<Integer> preorderTraversal(TreeNode root) {
    
      if(root!=null)
      {
      list.add(root.val);
      preorderTraversal(root.left);
      preorderTraversal(root.right);
    
      }
    
      return list;
      }
    }

     

    Latest Articles

    More Recipes Like This