zoukankan      html  css  js  c++  java
  • Deepest left leaf node in a binary tree

    Recursion

    1. selfcontained recursion
    2. global variables outside of recursion

    Recursion Design 

    1. Whenever reach to a qualified node, record the node reference and level for that node
    2. if meet next qualified node, compare the level, if larger, refresh the global node reference and level.
    3. Recursively do 1 and 2 recursively for left tree and right tree

    Data Structure 

        public class AVLTreeNode
        {
            public int data
            {
                get;
                set;
            }
    
            public AVLTreeNode leftChild
            {
                get;
                set;
            }
    
            public AVLTreeNode rightChild
            {
                get;
                set;
            }
    
            public int height
            {
                get;
                set;
            }
    
            public AVLTreeNode(int data)
            {
                this.data = data;
                this.height = 1;
            }
        }

    Source Code

       public class Result
        {
            public int MaxHight
            {
                get;
                set;
            }
    
            public AVLTreeNode ResultNode
            {
                get;
                set;
            }
        }
    
            // Find deepest left node
            public void FindDeepestLeftNode(AVLTreeNode node, bool isLeft, int height, Result result)
            {
                if (node == null)
                {
                    return;
                }
    
                if (isLeft)
                {
                    if (node.leftChild == null && node.rightChild == null && height > result.MaxHight)
                    {
                        result.ResultNode = node;
                        result.MaxHight = height;
                    }
                }
    
                FindDeepestLeftNode(node.leftChild, true, height + 1, result);
                FindDeepestLeftNode(node.rightChild, false, height + 1, result);
            }
    
            public AVLTreeNode GetDeepestLeftNode()
            {
                Result result = new Result()
                {
                    MaxHight = 0,
                    ResultNode = null
                };
    
                FindDeepestLeftNode(root, true, 0, result);
                return result.ResultNode;
            }

    Complexity

    Time complexity is O(N)

    Space complexity is O(N)

  • 相关阅读:
    centos 7 安装zabbix 4.0
    django Middleware
    初探paramiko
    python中的反射
    python异常处理
    双绞线
    简易的CMDB服务端
    4-初识Django Admin
    数据资产管理实践纲要
    matplotlib 散点图,为不同区域的点添加不同颜色
  • 原文地址:https://www.cnblogs.com/xuyanran/p/8456150.html
Copyright © 2011-2022 走看看