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)

  • 相关阅读:
    1048. Find Coins (25)
    return view 详解 MVC
    EF Power Tool 代码生成器 反向生成
    对新数据库使用 Code First
    一个成熟的网站的架构设计应该是这样的
    公司业务的设计思想感悟
    请给奋斗中的男人们一次机会
    大话西游感悟
    充满恶意的单词
    lisp的解释器
  • 原文地址:https://www.cnblogs.com/xuyanran/p/8456150.html
Copyright © 2011-2022 走看看