【数据结构与算法】二叉树基础知识与面试高频leetcode题目

目录

有根树介绍

二叉搜索树基础知识

二叉搜索树(Binary search Tree,BST)的性质:

二叉搜索树的搜索算法有三种:

高频leetcode面试题

98.验证二叉搜索树

递归算法。

中序遍历算法。

 235.二叉树搜索最近公共祖先 

一次遍历算法。

 236.二叉树的最近公共祖先

有根树介绍

用链式结构表示有根树。树的节点用对象表示,类似于链表,每个节点都有一个关键字key,还包括指向其他节点的指针。

下图是一个二叉树T,利用属性p、left、right存放指向父节点、左孩子和右孩子的节点的指针。如果x.p = NULL,则x是根节点,若x.left = NULL,则节点x没有左孩子,x.right 同理,属性T.root指向整棵树T的根节点,若T.root = NULL,则该树为空。

二叉树的表示方法可以推广大每个节点的孩子至多为常数k的任意类型的树。当孩子节点数无限制时,这种方法就失效了,因为我们不知道预先分配多少个属性,若孩子数K限制再一个很大的常数内,但若多数节点只有少量的孩子,也会浪费大量的存储空间。所以使用左孩子右兄弟的表示方法,如下图所示:

 类比于二叉树,每个节点都包括指向父节点的指针p,T.root指向根节点,每个节点包含两个指针:

  1. x.left-child 指向x最左边的孩子节点;
  2. x.right-sibling 指向x右侧相邻的兄弟节点;

二叉搜索树基础知识

二叉搜索树(Binary search Tree,BST)的性质:

假设x是二叉搜索树中的一个节点,若y是x左子树的一个节点,那么y.key <= x.key, 若y是右子树的一个节点,那么y.key >= x.key。

二叉搜索树的搜索算法有三种:

前序排序算法(preorder tree walk)(根-左-右) :遍历时先遍历根节点,之后是左节点和右节点;

中序排序算法(inorder tree walk)(左-根-右):遍历时先遍历左节点,之后是根节点和右节点;

后序排序算法(posorder tree walk)(左-右-根):遍历时先遍历右节点,之后是根节点和左节点;

前、中、后序 指的是 根节点的遍历顺序;n个节点的二叉树遍历的时间复杂度为O(n)。

高频leetcode面试题

98.验证二叉搜索树

98. 验证二叉搜索树 - 力扣(LeetCode) (leetcode-cn.com)https://leetcode-cn.com/problems/validate-binary-search-tree/

递归算法。

根据二叉搜索树性质:如果该二叉树的左子树不为空,则左子树上所有节点的值均小于它的根节点的值; 若它的右子树不空,则右子树上所有节点的值均大于它的根节点的值;它的左右子树也为二叉搜索树。

设计一个递归函数helper(root,lower,upper)进行递归判断,以root作为根的子树,子树所有的节点的值val都在(lower,upper)范围内,不满足条件直接返回,否则继递归。

复杂度分析

时间复杂度 : O(n),其中 nn 为二叉树的节点个数。在递归调用的时候二叉树的每个节点最多被访问一次,因此时间复杂度为 O(n)。

空间复杂度 : O(n),其中 n 为二叉树的节点个数。递归函数在递归过程中需要为每一层递归函数分配栈空间,所以这里需要额外的空间且该空间取决于递归的深度,即二叉树的高度。最坏情况下二叉树为一条链,树的高度为 n ,递归最深达到 n层,故最坏情况下空间复杂度为 O(n) 。

//cpp
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool helper(TreeNode* root,long long lower,long long upper){
        if (root == nullptr) { return true;}
        if (root->val <= lower || root->val >= upper) {return false;}
        return helper(root->left,lower,root->val) && helper(root->right,root->val,upper);
    }
    bool isValidBST(TreeNode* root) {
        return helper(root,LONG_MIN,LONG_MAX);
    }
};
#python3
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isValidBST(self, root: TreeNode) -> bool:
        # 递归函数helper
        def helper(node,lower=float('-inf'),upper=float('inf'))->bool:
            if not node:return True
            if (node.val <= lower or node.val >= upper):return False
            # 遍历右子树
            if not helper(node.right,node.val,upper):
                return False
            # 遍历左子树
            if not helper(node.left,lower,node.val):
                return False
            return True

注:

LONG_MINMinimum value for a variable of type long.-2147483647 - 1
LONG_MAXMaximum value for a variable of type long.214748364

中序遍历算法。

 二叉树中序遍历顺序为:左子树-根节点-右子树,它得到的值的序列一定为升序列,所以检查当前节点的值是否是大于前一个中序遍历得到的节点的值,使用栈来模拟中序遍历的过程。

INT_MINMinimum value for a variable of type int.-2147483647 - 1
INT_MAXMaximum value for a variable of type int.2147483647
//cpp
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool isValidBST(TreeNode* root) {
        stack<TreeNode*> stack;
        //初始化indorer
        long long inorder = (long long)INT_MIN - 1;
        while (!stack.empty() || root != nullptr){
            //遍历树节点,将节点压入栈中
            while (root != nullptr){
                //节点压入
                stack.push(root);
                // 左子树节点
                root = root->left;
            }
            root = stack.top();
            stack.pop();
            if (root->val <= inorder){
                return false;
            }
            inorder = root->val;
            root = root->right;
        }
        return true;
    }
};
# python3
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isValidBST(self, root: TreeNode) -> bool:
        stack,inorder = [],float('-inf')
        while stack or root:
            while root:
                stack.append(root)
                root = root.left
            root = stack.pop()
            if root.val <= inorder:
                return False
            inorder = root.val
            root = root.right
        return True

时间复杂度 : O(n),其中 n为二叉树的节点个数。二叉树的每个节点最多被访问一次,因此时间复杂度为 O(n)。

空间复杂度 : O(n),其中 n为二叉树的节点个数。栈最多存储 n 个节点,因此需要额外的 O(n) 的空间。

 235.二叉树搜索最近公共祖先 

235. 二叉搜索树的最近公共祖先 - 力扣(LeetCode) (leetcode-cn.com)https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree/

一次遍历算法。

从根节点开始遍历,若当前节点的值大于p和q,则p和q应该在当前节点的左子树,所以当前节点移动到它的左子节点;若当前节点的值小于p和q,则p和q应该在当前节点的右子树,所以当前节点移动到它的右子节点;若当前节点的值在p和q之间,则当前节点就是分叉点。

//cpp
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        TreeNode* ancestor = root;
        while (true){
            if (p->val < ancestor->val && q->val < ancestor->val){
                ancestor = ancestor->left;
            }
            else if (p->val > ancestor->val && q->val > ancestor->val){
                ancestor = ancestor->right;
            }
            else {break;}

        }
        return ancestor;
        
    }
};
# python3
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        ancestor = root
        while True:
            if (ancestor.val < p.val and ancestor.val < q.val):
                ancestor = ancestor.right
            elif (ancestor.val > p.val and ancestor.val > q.val):
                ancestor = ancestor.left
            else:
                break
        return ancestor
  • 时间复杂度:O(n),其中 n是给定的二叉搜索树中的节点个数,上述代码需要的时间与节点 p 和 q 在树中的深度线性相关,而在最坏的情况下,树呈现链式结构,p 和 q 一个是树的唯一叶子结点,一个是该叶子结点的父节点,此时时间复杂度为 Θ(n)。

  • 空间复杂度:O(1)。

 236.二叉树的最近公共祖先

236. 二叉树的最近公共祖先 - 力扣(LeetCode) (leetcode-cn.com)

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值