二叉树相关题

题目:在二叉树中找到一个节点中序遍历的下一个节点

1、有父指针。分两种情况

Node* FindNextNode(Node* node)
    {
        if (_root == NULL || node == NULL)
            return NULL;
        Node* next = NULL;
        //1、右不为空,找到右子树的最左节点即为下一个节点
        if (node->_right != NULL)
        {
            Node* right = node->_right;
            while (right->_left)
                right = right->_left;
            next = right;
        }
        //2、右子树为空,顺着父指针往上找,直到找到一个节点是其父节点的左孩子,则这个父节点就是下一个节点
        else
        {
            Node* parent = node->_parent;
            Node* cur = node;
            //如果parent不为空并且当前节点是parent的右孩子,则一直往上找
            while (parent && cur == parent->_right)
            {
                cur = parent;
                parent = parent->_parent;
            }
            next = parent;
        }
        return next;
    }

2、普通二叉树,借助中序遍历

//查找中序遍历的某个节点的下一个节点
    Node* FindNextNode(Node* node)
    {
        if (_root == NULL || node == NULL)
            return NULL;
        bool find = false;
        stack<Node*> s;
        Node* cur = _root;
        while (cur || !s.empty())
        {
            while (cur)
            {   
                s.push(cur);
                cur = cur->_LeftChild;
            }
            Node* top = s.top();
            s.pop();
            if (find)
                return top;
            if (top == node)
                find = true;
            cur = top->_RightChild;
        }
        if (s.empty())
            cout << "最后一个节点" << endl;
        return NULL;
    }

题目:判断一棵二叉树是否平衡(左子树和右子树的高度不超过1)

    bool Isbalance()
    {
        int depth = 0;
        return _Isbalance(_root,depth);
    }

//用后序遍历的方式遍历整课二叉树,在遍历到某一节点之后根据它左右节点的深度
//判断当前节点是否平衡,再计算当前节点的深度。知道遍历到根节点
    bool _Isbalance(Node*& root, int& depth)
    {
        if (root == NULL)
        {
            depth = 0;
            return true;
        }
        int left = 0;
        int right = 0;
        if (_Isbalance(root->_left, left) && _Isbalance(root->_right, right))
        {
            if (abs(left - right) <= 1)
            {
                depth = (left > right ? left + 1 : right + 1);
                return true;
            }
        }
        return false;
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值