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)

转载于:https://www.cnblogs.com/xuyanran/p/8456150.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值