Posted on by Kalkicode
Code Binary Tree

Diagonal traversal of binary tree in swift

Swift program for Diagonal traversal of binary tree. Here more information.

import Foundation
/* 
  Swift 4 program for
  Diagonal Traversal of Binary Tree
*/
// Binary Tree Node
class TreeNode
{
    var data: Int;
    var left: TreeNode? ;
    var right: TreeNode? ;
    init(_ data: Int)
    {
        // Set node value
        self.data = data;
        self.left = nil;
        self.right = nil;
    }
}
class BinaryTree
{
    var root: TreeNode? ;
    init()
    {
        self.root = nil;
    }
    // Find diagonal elements
    func getDiagonalView(_ node: TreeNode? , 
                        _ distance : Int, 
                        _ record:inout [Int: [Int]])
    {
        if (node  != nil)
        {
            if (!record.keys.contains(distance))
            {
                // Add new diagonal level
                record[distance] = [Int]();
            }
            // Add node
            record[distance]!.append(node!.data);
            // Visit to left subtree
            self.getDiagonalView(node!.left, distance + 1, &record);
            // Visit to right subtree
            self.getDiagonalView(node!.right, distance, &record);
        }
    }
    func diagonalView()
    {
        // This is store result
        var record: [Int: [Int]] = [Int: [Int]]();
        self.getDiagonalView(self.root, 0, &record);
        var distance: Int = 0;
        while (distance < record.count)
        {
            // This loop display diagonal element
            for v in record[distance]!
            {
                print("",v, terminator: " ");
            }
            print();
            distance += 1;
        }
    }
    static func main()
    {
        // Create new tree
        let tree: BinaryTree = BinaryTree();
        /*
         Make A Binary Tree
         -----------------------
              10
             / \ 
            /   \
           2     4
          /    /  \
         3    6    \
             / \    \
            1   7    5
               /    /
              9    3 
        */
        // Add tree node
        tree.root = TreeNode(10);
        tree.root!.left = TreeNode(2);
        tree.root!.left!.left = TreeNode(3);
        tree.root!.right = TreeNode(4);
        tree.root!.right!.right = TreeNode(5);
        tree.root!.right!.left = TreeNode(6);
        tree.root!.right!.left!.left = TreeNode(1);
        tree.root!.right!.right!.left = TreeNode(3);
        tree.root!.right!.left!.right = TreeNode(7);
        tree.root!.right!.left!.right!.left = TreeNode(9);
        tree.diagonalView();
    }
}
BinaryTree.main();

Output

 10  4  5
 2  6  7  3
 3  1  9

Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment