144. Binary Tree Preorder Traversal

 Problem Statement


Given the root of a binary tree, return the preorder traversal of its nodes' values.

 

Example 1:

Input: root = [1,null,2,3]
Output: [1,2,3]

Example 2:

Input: root = []
Output: []

Example 3:

Input: root = [1]
Output: [1]

Example 4:

Input: root = [1,2]
Output: [1,2]

Example 5:

Input: root = [1,null,2]
Output: [1,2]

 

Constraints:

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

 

Follow up: 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() {}

 *     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> preorderTraversal(TreeNode root) 

    {

        ArrayList<Integer> list = new ArrayList<>();

        Stack<TreeNode> stack = new Stack<>();

        if(root == null)

            return list;

        stack.push(root);

        while(stack.size()>0)

        {

            TreeNode temp = stack.pop();

            list.add(temp.val);

            if(temp.right != null)

                stack.push(temp.right);

            if(temp.left != null)

                stack.push(temp.left);

        }

        return list;

    }

}


Linked List Cycle in leetcode

Description:-

Given head, the head of a linked list, determine if the linked list has a cycle in it.

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.

Return true if there is a cycle in the linked list. Otherwise, return false.

Example - 1 :

Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).

Example 2:

Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.

Example 3:

Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.

Constraints:

  • The number of the nodes in the list is in the range [0, 104].
  • -105 <= Node.val <= 105
  • pos is -1 or a valid index in the linked-list.

 

Follow up: Can you solve it using O(1) (i.e. constant) memory?


Program:- 

/**

 * Definition for singly-linked list.

 * class ListNode {

 *     int val;

 *     ListNode next;

 *     ListNode(int x) {

 *         val = x;

 *         next = null;

 *     }

 * }

 */

public class Solution {

    public boolean hasCycle(ListNode head) {

        ListNode slowPtr=head;

        ListNode fastPtr=head;

        while(fastPtr!=null && fastPtr.next!=null)

        {

            slowPtr=slowPtr.next;

            fastPtr=fastPtr.next.next;

            if(slowPtr==fastPtr)

                return true;

        }

        return false;  

    }

}



                                 Unions



Definition:

  • A union is a special data type available in C that allows the storage of different data types in the same memory location. 
  • Unlike unions structures can stores different data types in different locations.
  • You can define a union with many members, but only one member can contain a value at any given time. 
  • Unions provide an efficient way of using the same memory location for multiple-purpose.


Declaration:

union [union tag] {

   member definition;

   member definition;

   ...

   member definition;

} [declaring one or more union variables]; 


Giving the union tag is optional it works without tag also.


Example:

union Data {

   int i;

   float f;

   char str[45];

} data;


  • Now, a variable of Data type can store an integer, a floating-point number, or a string of characters. It means a single variable(data), i.e., the same memory location, can be used to store multiple types of data. 
  • You can use any built-in or user-defined data types inside a union based on your requirement.
  • The memory occupied by a union will be large enough to hold the largest member of the union. 
  • For example, in the above example, Data type will occupy 45 bytes of memory space because this is the maximum space that can be occupied by a character string. The following example displays the total memory size occupied by the above union example.

Accessing Union Members

Same as Structures To access any member of a union, we use the member access operator (.), and The member access operator is coded as a period between the union variable name and the union member that we wish to access.

Example:

#include <stdio.h>

#include <string.h>

union Shs{

 int i;

 float f;

};

int main( ) {

 union Shs d;        

 data.i = 10;

data.f = 220.5;

strcpy( d.str, "C Programming");

printf( "d.i : %d\n", data.i);

printf( "d.f : %f\n", data.f);

printf( "d.str : %s\n", data.str);

return 0;

}

Output:

d.i : 1917853763

d.f : 4122360580327794860452759994368.000000

d.str : C Programming

Explaination:

As the data is stored in the same location the integer data and the float data has been corrupted or overwritten by the string data so that when we call integer and float data we get some corrupted value and we can see the String data is displayed correctly as it was stored at the last in the union.

if the code is like this

data.i = 10;

printf( "d.i : %d\n", data.i);

data.f = 220.5;

printf( "d.f : %f\n", data.f);

strcpy( d.str, "C Programming");

printf( "d.str : %s\n", d.str);

then the output will be:

d.i : 10

d.f : 220.500000

d.str : C Programming



Note: More examples will be covered in Problems on the C page

Similarly, you can also learn the structures, arrays, and pointers concept also here

If you have any doubts or you want us to create some more concepts or if you can't solve any problems please give it in the form of your comments.


If you like the content we had given and understood it well then give your valuable rating for this page and comment on your experience in the comment box .