树的遍历

163 阅读1分钟

学习目标:

  • 学习树的遍历;
  • 二叉搜索树的基础知识;
  • 练习python语法;
leetcode学习资料树的遍历

树的遍历方式:

  • 中序遍历 --递归
  • 后序遍历 --递归
  • 前序遍历 --递归
  • 层序遍历

遍历模板

// (二叉树)后序遍历
  const postorder=(root)=>{
         if(!root){
            return;
        }
        postorder(root.left);
        postorder(root.right);
        res.push(root.val);
    }
// (二叉树)中序遍历
  const inorder=(root)=>{
         if(!root){
            return;
        }
        postorder(root.left);
        res.push(root.val);
        postorder(root.right);
    }
  //(二叉树) 前序遍历
  const preorder=(root)=>{
         if(!root){
            return;
        }
        res.push(root.val);
        postorder(root.left);
        postorder(root.right);
    }
// 层序遍历
const levelOrder=(root)=>{
   // 判空
   if(!root){
        return [];
    }
    
    //初始化队列
    let queue=[];
    queue.push(root);
    
    //存放结果数据
    let res=[];
    
    //循环队列
    while(queue.length){
       let arr=[];//存放当前层结果的数组
       for(let i=0,len=queue.length;i<len;++i){
       
           //获取队头数据,并删除队头数据
           let node=queue.shift();
            arr.push(node.val);
            
            //队列存放下一层数据
            node.left && queue.push(node.left);
            node.right && queue.push(node.right);
       }
       //存放当前层数据
       res.push(arr);
    }
    
    //返回结果
    return res;
 }

二叉搜索树(Binary Search Tree)

  • 二叉搜索树特性:
  1. 左子树上所有结点的值都小于它的根结点的值;
  2. 右子树上所有结点的值都大于它的根结点的值;
  3. 左右子树也分别都是二叉搜索树;
  4. 中序遍历:升序排列;
  • 二叉搜索树的常规在操作
  1. 查找(平均时间复杂度O(logn));
  2. 插入(平均时间复杂度O(logn));
  3. 删除(平均时间复杂度O(logn));

二叉搜索树的实现(查找、插入、删除)

练习

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var inorderTraversal = function(root) {
  
    let arr=[];
    const inOrder=(root)=>{
        if(root===null) return;
        inOrder(root.left);
        arr.push(root.val);
        inOrder(root.right);
    }
    inOrder(root);
    return arr;

};

语言:python

# 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 inorderTraversal(self, root: TreeNode) -> List[int]:
        res=[];
        def inorder(root):
            if not root:
                return;
            inorder(root.left);
            res.append(root.val);
            inorder(root.right);
        inorder(root);
        return res;         

语言:javascript

/**
 * // Definition for a Node.
 * function Node(val,children) {
 *    this.val = val;
 *    this.children = children;
 * };
 */

/**
 * @param {Node|null} root
 * @return {number[]}
 */
var postorder = function(root) {
    const res=[];
    const order=(root)=>{
        if(root===null){
            return;
        }

        for(let i=0,len=root.children.length;i<len;++i){
            order(root.children[i]);
        }
    
        res.push(root.val);
    }
    order(root);
    return res;
};

语言:python

"""
# Definition for a Node.
class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children
"""

class Solution:
    def postorder(self, root: 'Node') -> List[int]:
        res=[];
        def order(root):
            if root == None:
                return;
            for item in root.children:
                order(item)
            else:
                res.append(root.val);
        order(root);
        return res;

语言:javassript

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var levelOrder = function(root) {

    if(!root){
        return [];
    }
    let queue=[];
    queue.push(root);
    let res=[];
    while(queue.length){
       let arr=[];
       for(let i=0,len=queue.length;i<len;++i){
           let node=queue.shift();
            arr.push(node.val);
            node.left && queue.push(node.left);
            node.right && queue.push(node.right);
       }
       res.push(arr);
    }
    return res;
};