<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Aman Pal on Medium]]></title>
        <description><![CDATA[Stories by Aman Pal on Medium]]></description>
        <link>https://medium.com/@aman.pal21?source=rss-562609c89ad4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*4HlAlbEujOlj5Nwt</url>
            <title>Stories by Aman Pal on Medium</title>
            <link>https://medium.com/@aman.pal21?source=rss-562609c89ad4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 05:31:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aman.pal21/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Wonders of Binary Trees: Unveiling Expression Evaluation and Huffman Encoding]]></title>
            <link>https://medium.com/@aman.pal21/the-wonders-of-binary-trees-unveiling-expression-evaluation-and-huffman-encoding-5fb89366b9c0?source=rss-562609c89ad4------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fb89366b9c0</guid>
            <category><![CDATA[expression-tree]]></category>
            <category><![CDATA[huffman-encoding]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[binary-tree]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Aman Pal]]></dc:creator>
            <pubDate>Wed, 24 Apr 2024 14:26:22 GMT</pubDate>
            <atom:updated>2024-04-25T04:17:57.454Z</atom:updated>
            <content:encoded><![CDATA[<p>Today, we embark on a fascinating journey through the intricate world of binary trees and their captivating applications in expression evaluation and Huffman encoding.</p><p>Our story begins with the binary tree, a hierarchical data structure that resembles a tree-like structure with each node having at most two children — a left child and a right child. This simple yet powerful construct forms the backbone of numerous algorithms and data manipulation techniques.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*Zstzgk_unNC1-Lu9GzTisQ.png" /><figcaption><strong>A balanced binary tree</strong></figcaption></figure><p>Here are the key characteristics of binary trees:</p><p>1. <strong>Root Node:</strong> The topmost node in the tree, with no parent.</p><p>2. <strong>Parent Nodes:</strong> Each node (except the root) has exactly one parent.</p><p>3. <strong>Child Nodes:</strong> Each node can have at most two children, which are referred to as the left child and the right child.</p><p>4. <strong>Leaf Nodes</strong>: Nodes with no children are called leaf nodes or terminal nodes.</p><p>5. <strong>Internal Nodes:</strong> Nodes with at least one child are called internal nodes.</p><p><strong>Binary trees have immense importance in computer science and find their applications in the following areas</strong>:</p><p>· <strong>Binary Search Trees (BST)</strong>: In a binary search tree, each node’s left child contains a value less than its parent node’s value, and each right child’s value is greater than its parent node’s value. BSTs are used for efficient searching, insertion, and deletion operations.</p><p>· <strong>Expression Trees</strong>: Binary trees can be used to represent mathematical expressions. Each node represents an operator or operand, and the tree structure represents the order of operations.</p><p>· <strong>Binary Heap</strong>: Binary heaps are binary trees that satisfy the heap property. They are commonly used to implement priority queues, where the highest (or lowest) priority element can be efficiently retrieved.</p><p>· <strong>File Systems</strong>: Binary trees are often used to represent file systems. Each directory is a node, and its children are files or subdirectories.</p><p>· <strong>Syntax Trees</strong>: Binary trees can represent the syntactic structure of sentences or programs. Each node represents a syntactic construct, and the tree structure captures the hierarchical relationships between these constructs.</p><p>Today we will be having a look at two of these applications expression tree evaluation and huffmann encoding.</p><h4><strong>Expression Evaluation: Where Mathematical Elegance Meets Computational Efficiency</strong></h4><p>Have you ever wondered how your computer solves complex mathematical expressions with such ease? The answer lies in the realm of expression trees. By converting an infix expression (like 3 + ((5+9)*2)) into a binary tree structure, the computer can traverse the tree and evaluate the expression in an efficient and systematic manner.</p><p>The algorithms involved in constructing and evaluating expression trees are nothing short of ingenious. First, the infix expression is converted into a postfix or prefix notation, which can then be used to construct the expression tree. Once the tree is built, a recursive algorithm traverses it, evaluating each subtree and combining the results according to the operators.</p><p><strong>A. Algorithms used in expression tree evaluation:</strong></p><p>· <strong>Construction</strong>: This algorithm constructs an expression tree from a given infix expression. It typically involves converting the infix expression to either postfix or prefix notation, then using a stack to build the expression tree.</p><p>· <strong>Traversal</strong>: Traversal algorithms are used to visit nodes of the expression tree in a specific order. Common traversal methods include in-order, pre-order, and post-order traversal. For evaluation, post-order traversal is often used.</p><p>· <strong>Evaluation</strong>: This algorithm evaluates the expression tree to compute the result of the mathematical expression represented by the tree. It typically involves traversing the tree in post-order, recursively evaluating each subtree and combining results according to the operators.</p><p>· <strong>Conversion</strong>: Conversion algorithms transform one form of mathematical expression into another. For example, converting an infix expression to postfix or prefix notation, or vice versa. These conversions can facilitate easier evaluation or storage of expressions</p><p><strong>B.<em> Pseudo-code:</em></strong></p><p><em>FUNCTION EvaluateExpression(expression)<br> infix_expression ← GET_USER_INPUT()<br> postfix_expression ← CONVERT_INFIX_TO_POSTFIX(infix_expression)<br> expression_tree ← CONSTRUCT_EXPRESSION_TREE(postfix_expression)<br> result ← EVALUATE_EXPRESSION_TREE(expression_tree)<br> PRINT(result)</em></p><p><em>FUNCTION CONVERT_INFIX_TO_POSTFIX(infix_expression)<br> postfix ← EMPTY_STRING<br> stack ← EMPTY_STACK<br> FOR each token IN infix_expression<br> IF token IS_DIGIT<br> postfix ← postfix + token<br> ELSE IF token IS_OPERATOR<br> WHILE stack IS_NOT_EMPTY AND PEEK(stack) IS_OPERATOR AND HAS_HIGHER_PRECEDENCE(PEEK(stack), token)<br> postfix ← postfix + POP(stack)<br> END WHILE<br> PUSH(stack, token)<br> ELSE IF token IS_LEFT_PARENTHESIS<br> PUSH(stack, token)<br> ELSE IF token IS_RIGHT_PARENTHESIS<br> WHILE PEEK(stack) IS_NOT_LEFT_PARENTHESIS<br> postfix ← postfix + POP(stack)<br> END WHILE<br> POP(stack) // Discard left parenthesis<br> END IF<br> END FOR<br> WHILE stack IS_NOT_EMPTY<br> postfix ← postfix + POP(stack)<br> END WHILE<br> RETURN postfix</em></p><p><em>FUNCTION CONSTRUCT_EXPRESSION_TREE(postfix_expression)<br> stack ← EMPTY_STACK<br> FOR each token IN postfix_expression<br> IF token IS_DIGIT<br> node ← CREATE_NODE(token)<br> PUSH(stack, node)<br> ELSE IF token IS_OPERATOR<br> right_operand ← POP(stack)<br> left_operand ← POP(stack)<br> node ← CREATE_NODE(token, left_operand, right_operand)<br> PUSH(stack, node)<br> END IF<br> END FOR<br> RETURN POP(stack) // The root of the expression tree</em></p><p><em>FUNCTION EVALUATE_EXPRESSION_TREE(node)<br> IF IS_LEAF_NODE(node)<br> RETURN node.value<br> ELSE<br> left_value ← EVALUATE_EXPRESSION_TREE(node.left_child)<br> right_value ← EVALUATE_EXPRESSION_TREE(node.right_child)<br> result ← APPLY_OPERATION(node.value, left_value, right_value)<br> RETURN result</em></p><p><strong>C. Example:</strong></p><p>infix expression: 3 + ((5+9)*2)</p><p>postfix expression:<strong> </strong>3 5 9 + 2 *+</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*ICj6Gnh79XKSS0isf1HAMg.png" /><figcaption><strong>Expression Tree Formed</strong></figcaption></figure><p>On evaluating this evaluation tree we get the answer as 31.</p><p><strong>D. Analysis:</strong></p><p><strong>Space complexity:</strong></p><ul><li><strong>infix_to_postfix and prefix_to_postfix:</strong></li></ul><p><strong>O(n)</strong>, where N is the length of the input expression. This is due to the use of a stack to store operators and operands, which scales linearly with the input size.</p><ul><li><strong>construct_expression_tree:</strong></li></ul><p><strong>O(n)</strong>, again due to the use of a stack to store nodes during tree construction.</p><ul><li><strong>evaluate_expression_tree:</strong></li></ul><p>The space complexity of a balanced binary tree is <strong>O(n).</strong></p><p><strong>Time complexity:</strong></p><ul><li><strong>infix_to_postfix and prefix_to_postfix:</strong></li></ul><p><strong>O(n)</strong>, each character in the input is processed once, with constant-time operations for comparisons and stack operations.</p><ul><li><strong>construct_expression_tree:</strong></li></ul><p><strong>O(n)</strong> Similar to infix_to_postfix, each character in the postfix expression is processed once with constant-time operations.</p><ul><li><strong>evaluate_expression_tree:</strong></li></ul><p>Therefore, the total time complexity is proportional to the number of nodes in the tree, which is <strong>O(n)</strong>.</p><h3>Huffman Encoding:</h3><p>Now, let’s embark on a journey into the realm of data compression, where Huffman encoding reigns supreme. This ingenious technique, named after its creator, David A. Huffman, allows us to compress data by assigning shorter codes to more frequent characters, thereby reducing the overall file size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*aFqhdEPqweJunoxl4-OeOQ.png" /></figure><p>In Huffman Encoding, several algorithms are utilized, including tree traversal, priority queue operations, and recursive algorithms for tree construction. Here’s a breakdown of the algorithms involved:</p><p><strong>1. Tree Traversal:</strong></p><ul><li><strong>In-order Traversal</strong>: Used to generate the Huffman codes by traversing the constructed Huffman tree. During traversal, left branches are assigned ‘0’ and right branches are assigned ‘1’.</li><li><strong>Depth-First Traversal</strong>: This traversal method is often employed during the construction of the Huffman tree. Depth-first search algorithms like pre-order, in-order, and post-order traversal may be used.</li></ul><p><strong>2. Priority Queue Operations:</strong></p><ul><li><strong>Insertion</strong>: As each character’s frequency is evaluated, it’s inserted into the priority queue.</li><li><strong>Extraction/Deletion</strong>: During tree construction, nodes with the lowest frequencies are extracted from the priority queue to build the tree.</li></ul><p><strong>3. Greedy Algorithm:</strong></p><ul><li>Huffman encoding employs a greedy approach, where characters with the lowest frequency are merged together iteratively to build the Huffman tree. This involves selecting the two lowest frequency nodes from the priority queue in each iteration.</li></ul><p><strong>4. Recursive Algorithms:</strong></p><ul><li><strong>Tree Construction</strong>: The construction of the Huffman tree often involves a recursive algorithm. The process continues recursively until only one node remains in the priority queue.</li><li><strong>Code Generation</strong>: Generating Huffman codes for each character involves a recursive traversal of the constructed Huffman tree.</li></ul><h4>Pseudo-code:</h4><p><em>FUNCTION Huffman_Encode(data)<br> freq_map ← Calculate_Frequency(data)<br> priority_queue ← Initialize_Priority_Queue(freq_map)<br> root ← Build_Huffman_Tree(priority_queue)<br> codes ← EMPTY_DICTIONARY<br> Generate_Codes(root, “”, codes)<br> encoded_data ← Encode_Data(data, codes)<br> RETURN encoded_data</em></p><p><em>FUNCTION Calculate_Frequency(data)<br> freq_map ← EMPTY_DICTIONARY<br> FOR each character IN data<br> IF character NOT IN freq_map<br> freq_map[character] ← 1<br> ELSE<br> freq_map[character] ← freq_map[character] + 1<br> RETURN freq_map</em></p><p><em>FUNCTION Initialize_Priority_Queue(freq_map)<br> priority_queue ← EMPTY_PRIORITY_QUEUE<br> FOR each character, frequency IN freq_map<br> node ← CREATE_NODE(character, frequency)<br> ENQUEUE(priority_queue, node)<br> RETURN priority_queue</em></p><p><em>FUNCTION Build_Huffman_Tree(priority_queue)<br> WHILE SIZE(priority_queue) &gt; 1<br> left_node ← DEQUEUE(priority_queue)<br> right_node ← DEQUEUE(priority_queue)<br> new_node ← CREATE_NODE(left_node.frequency + right_node.frequency)<br> new_node.left_child ← left_node<br> new_node.right_child ← right_node<br> ENQUEUE(priority_queue, new_node)<br> RETURN DEQUEUE(priority_queue) // The root of the Huffman tree</em></p><p><em>FUNCTION Generate_Codes(root, current_code, codes)<br> IF IS_LEAF_NODE(root)<br> codes[root.character] ← current_code<br> ELSE<br> IF root.left_child IS NOT NULL<br> Generate_Codes(root.left_child, current_code + “0”, codes)<br> IF root.right_child IS NOT NULL<br> Generate_Codes(root.right_child, current_code + “1”, codes)</em></p><p><em>FUNCTION Encode_Data(data, codes)<br> encoded_data ← EMPTY_STRING<br> FOR each character IN data<br> encoded_data ← encoded_data + codes[character]<br> RETURN encoded_data</em></p><p><strong>Example:</strong></p><p>Let’s take the following set of characters and their frequencies:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*GLmsXMe-bik1RU0E6tSScw.png" /><figcaption>Frequency Table</figcaption></figure><p>Using Huffman encoding, we can construct the binary tree as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*tiXT5xeWIzclhtrANMKwOA.png" /><figcaption>The corresponding Huffman tree</figcaption></figure><p><strong>Analysis:</strong></p><p><strong>Time Complexity:</strong></p><ul><li>Calculating frequencies: O(n)</li><li>Building priority queue: O(n log n)</li><li>Building Huffman tree: O(n log n)</li><li>Generating codes: O(n)</li><li>Encoding data: O(n) Overall, the time complexity is dominated by the sorting operations, making it O(n log n) where n is the number of characters in the input data.</li></ul><p><strong>Space Complexity:</strong></p><ul><li>Storing frequency map: O(n)</li><li>Priority queue: O(n)</li><li>Huffman tree: O(n)</li><li>Codes: O(n) Overall, the space complexity is O(n).</li></ul><p><strong>Applications of Expression Trees:</strong></p><p><strong>1. Compiler Design and Parsing: </strong>Expression trees are fundamental in compilers for parsing and evaluating arithmetic expressions during the compilation process. They help in converting infix expressions to postfix or prefix notation, which can be easier to evaluate or translate into machine code.</p><p><strong>2. Mathematics and Symbolic Computation: </strong>Symbolic computation systems utilize expression trees for simplifying and evaluating mathematical expressions symbolically. These systems can perform operations like differentiation, integration, and simplification on algebraic expressions.</p><p><strong>3. Computer Algebra Systems (CAS): </strong>CAS software, used extensively in mathematics and engineering, employs expression trees for symbolic manipulation of mathematical expressions. These systems enable users to perform complex mathematical operations symbolically rather than numerically.</p><p><strong>4. Graphical Calculator Applications: </strong>Expression trees can be used in graphical calculator applications to parse, evaluate, and plot mathematical functions entered by the user. They provide an intuitive way to visualize and interact with mathematical expressions.</p><p><strong>5. Equation Solvers and Numerical Analysis: </strong>In numerical analysis, expression trees play a role in solving equations numerically by representing mathematical models or functions. They can be used in root-finding algorithms or optimization techniques to solve equations efficiently.</p><p><strong>Application of Huffman Encoding:</strong></p><ul><li><strong>Data Compression:</strong> Huffman encoding is extensively used in file compression algorithms like ZIP, GIF, and JPEG.</li><li><strong>Telecommunication:</strong> It is used in various communication systems to reduce the amount of data that needs to be transmitted.</li><li><strong>Encryption:</strong> Huffman coding is also employed in cryptographic systems to represent data efficiently.</li></ul><h4>Conclusion:</h4><p>As we bid farewell to this captivating journey, we are left with a newfound appreciation for the ingenuity and versatility of binary trees. From the elegant evaluation of mathematical expressions to the art of data compression, these structures have proven to be invaluable tools in the realm of computer science.</p><p>Whether you’re a programmer, a mathematician, or a curious mind seeking to unravel the mysteries of the digital world, the study of binary trees and their applications will undoubtedly enrich your understanding and ignite your passion for problem-solving.</p><p>So, embrace the beauty of these data structures, and let them guide you through the intricate realms of expression evaluation, data compression, and beyond!</p><h4>References:</h4><p><strong>Huffman Coding:</strong></p><ul><li><a href="https://ocw.mit.edu/courses/6-046j-design-and-analysis-of-algorithms-spring-2012/resources/mit6_046js12_lec19/">https://ocw.mit.edu/courses/6-046j-design-and-analysis-of-algorithms-spring-2012/resources/mit6_046js12_lec19/</a> (MIT OpenCourseware lecture notes)</li><li><a href="https://catalog.wmich.edu/preview_program.php?catoid=29&amp;poid=8590&amp;returnto=1232">https://catalog.wmich.edu/preview_program.php?catoid=29&amp;poid=8590&amp;returnto=1232</a> (This reference explains Huffman coding with a focus on binary trees)</li><li><a href="https://en.wikipedia.org/wiki/Huffman_coding">https://en.wikipedia.org/wiki/Huffman_coding</a></li></ul><p><strong>Binary Trees:</strong></p><ul><li><a href="https://en.wikipedia.org/wiki/Binary_search_tree">https://en.wikipedia.org/wiki/Binary_search_tree</a> (This Wikipedia article provides a general overview of binary trees)</li><li><a href="https://medium.com/tag/binary-tree">https://medium.com/tag/binary-tree</a> (This Medium article discusses both expression evaluation and Huffman coding using binary trees)</li><li>GeeksforGeeks: <a href="https://www.geeksforgeeks.org/evaluation-of-expression-tree/">https://www.geeksforgeeks.org/evaluation-of-expression-tree/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fb89366b9c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>