数据结构与算法-二叉树


1 二叉树的基本结构

二叉树的基本结构

public static class TreeNode {
    int val;
    TreeNode left; // 左子节点
    TreeNode right;// 右子节点
    
    TreeNode(int val){
        this.val = val;
    }
}

2 二叉树的递归遍历

2.1 递归前序遍历

输出当前节点 → \rightarrow 输出左子节点 → \rightarrow 输出右子节点

coding

 /**
  * 二叉树的前序遍历
  * @param root
  */
 public static void preOrderRecur(TreeNode root){
     if (root == null){
         return;
     }
     System.out.print(root.val + " ");
     preOrderRecur(root.left);
     preOrderRecur(root.right);
 }

二叉树基本结构中的二叉树使用前序遍历输出节点如下 :
1 → \rightarrow 2 → \rightarrow 4 → \rightarrow 5 → \rightarrow 3 → \rightarrow 6 → \rightarrow 7

2.2 递归中序遍历

coding

public static void inOrderRecur(TreeNode root){
    if (root == null){
        return;
    }
    inOrderRecur(root.left);
    System.out.println(root.val + " ");
    inOrderRecur(root.right);
}

二叉树基本结构中的二叉树使用中序遍历输出节点如下 :
4 → \rightarrow 2 → \rightarrow 5 → \rightarrow 1 → \rightarrow 6 → \rightarrow 3 → \rightarrow 7

输出左子节点 → \rightarrow 输出父节点 → \rightarrow 输出右子节点

2.3 递归后序遍历

coding

public static void posOrderRecur(TreeNode root){
    if (root == null){
        return;
    }
    posOrderRecur(root.left);
    posOrderRecur(root.right);
    System.out.print(root.val + " ");
}

二叉树基本结构中的二叉树使用后序遍历输出节点如下 :
4 → \rightarrow 5 → \rightarrow 2 → \rightarrow 6 → \rightarrow 7 → \rightarrow 3 → \rightarrow 1

二叉树的递归遍历使用了递归调用的栈机制


3 二叉树的非递归遍历

3.1 非递归前序遍历

/**
 * 二叉树 前序遍历 非递归方式
 * @param root
 */
public static void preOrderNonRecur(TreeNode root){
   if (root == null) {
       return;
   }
   Stack<TreeNode> stack = new Stack<>();
   stack.push(root);
   while (!stack.isEmpty()){
      root = stack.pop();
      System.out.print(root.val + " ");
      if (root.right != null){
          stack.push(root.right);
      }
      if (root.left != null){
          stack.push(root.left);
      }
   }
}

3.2 非递归中序遍历

/**
 * 二叉树的中序遍历 非递归方式
 * @param root
 */
public static void inOrderNonRecur(TreeNode root){
    if (root == null){
        return;
    }
    Stack<TreeNode> stack = new Stack<>();
    while (!stack.isEmpty() || root != null){
        if (root != null){
            stack.push(root);
            root = root.left;
        } else { // 节点的左子节点为空
            // 从栈中弹出一个
            root = stack.pop();
            System.out.println(root.val + " ");
            // 右边节点进栈
            root = root.right;
        }
    }
}

3.3 非递归后序遍历


    public static void posOrderUnRecur(TreeNode root){
        if (root == null){
            return;
        }
        Stack<TreeNode> s1 = new Stack<>();
        Stack<TreeNode> s2 = new Stack<>();
        s1.push(root);
        while (!s1.isEmpty()){
            root = s1.pop();
            s2.push(root);
            // 左边先进栈
            if (root.left != null){
                s1.push(root);
            }
            // 右边进栈
            if (root.right != null){
                s1.push(root);
            }
        }
        while (!s2.isEmpty()){
            System.out.println(s2.pop().val + " ");
        }
    }

3.4 leetcode 题目

  1. 给你二叉树的根节点 root ,返回它节点值的前序遍历。
    数据范围:二叉树的节点数量满足 1 ≤ n ≤ 100 1≤n≤100 1n100 ,二叉树节点的值满足 1 ≤ v a l ≤ 100 1≤val≤100 1val100 ,树的各节点的值各不相同
/**
  * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
  *
  * 
  * @param root TreeNode类 
  * @return int整型一维数组
  */
 public int[] preorderTraversal (TreeNode root) {
     // write code here
     if(root == null){
       return null;
     }
     List<Integer> list = new ArrayList<>();
     Stack<TreeNode> stack = new Stack<>();
     stack.push(root);
     while(!stack.isEmpty()){
         root = stack.pop();
         list.add(root.val);
         // 前序遍历 右边先进栈
         if(root.right != null){
            stack.push(root.right); 
         }
         // 左边进栈
         if(root.left != null){
             stack.push(root.left);
         }
     }
     int[] retArr = new int[list.size()];
     for(int i = 0;i < list.size();++i){
       retArr[i] = list.get(i);
     }         
     return retArr;
 }
  1. 给定一个二叉树的根节点root,返回它的中序遍历结果。
    数据范围:树上节点数满足 0 ≤ n ≤ 1000 0≤n≤1000 0n1000,树上每个节点的值满足 − 1000 ≤ v a l ≤ 1000 −1000≤val≤1000 1000val1000
    进阶:空间复杂度 O ( n ) O(n) O(n),时间复杂度 O ( n ) O(n) O(n)
/**
   * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
   *
   * 
   * @param root TreeNode类 
   * @return int整型一维数组
   */
  public int[] inorderTraversal (TreeNode root) {
      // write code here
      if (root == null){
        return new int[0];
      }
      Stack<TreeNode> stack = new Stack<>();
      List<Integer> list = new ArrayList<>();
      while(!stack.isEmpty() || root != null){
         if(root != null){
            stack.push(root);
            root = root.left;
         } else {
            root = stack.pop();
            list.add(root.val);
            root = root.right;
         }
      }
      int[] resArr = new int[list.size()];
      for(int i = 0;i < list.size();i++){
        resArr[i] = list.get(i);
      }
      return resArr;
  }
  1. 给定一个二叉树,返回他的后序遍历的序列。
    后序遍历是值按照 左节点->右节点->根节点 的顺序的遍历。
    数据范围:二叉树的节点数量满足 1 ≤ n ≤ 100 1≤n≤100 1n100,二叉树节点的值满足 1 ≤ v a l ≤ 100 1≤val≤100 1val100 ,树的各节点的值各不相同
import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @return int整型一维数组
     */
    public int[] postorderTraversal (TreeNode root) {
        // write code here
        if(root != null){
           Stack<TreeNode> s1 = new Stack<>();
           Stack<TreeNode> s2 = new Stack<>();
           List<Integer> list = new ArrayList<>();
           s1.push(root);
           while(! s1.isEmpty()){
              root = s1.pop();
              s2.push(root);
              // 左边先进第一个栈s1 然后边后出第一个栈s1 后入s2 先出s2
              if(root.left != null){
                 s1.push(root.left); 
              }
              if(root.right != null){
                  s1.push(root.right);
              }
           }
           while(!s2.isEmpty()){
              list.add(s2.pop().val);
           }
           int[] retArr = new int[list.size()];
           for(int i = 0; i < list.size();++i){
              retArr[i] = list.get(i);
           } 
           return retArr;
        }
        return new int[0];
    }
}

4 二叉树的宽度优先遍历

遍历方法及步骤
使用队列,头先进队列,从头里面取出一个节点,然后左子节点先进队列,然后右子节点进队列,周而复始,直到队列为空

二叉树宽度优先遍历图解如 :

在这里插入图片描述

coding

/**
  *  二叉树的宽度优先遍历
  * @param root
  */
 public static void widthFirstTraversal(TreeNode root){
     if (root == null){
         return;
     }
     // 队列 双向链表可以当做队列
     Queue<TreeNode> queue = new LinkedList<>();
     queue.add(root);
     while (!queue.isEmpty()){
         // 从队里中取出一个节点 取出就打印
         root = queue.poll();
         System.out.print(root.val + " ");
         if (root.left != null){
             queue.add(root.left);
         }
         if (root.right != null){
             queue.add(root.right);
         }
     }
     System.out.println();
 }


5 求二叉树的最大宽度

使用宽度优先遍历,计算出每一层的节点个数,每来到一个新的层,就计算一次最大的节点个数

/**
 * 求二叉树的最大宽度
 * @param root
 * @return
 */
public static int getMaxWidth(TreeNode root){
    if (root == null){
        return 0;
    }
    Queue<TreeNode> queue = new LinkedList<>();
    queue.add(root);

    // 每一个节点所在的层
    Map<TreeNode,Integer> nodeMap = new HashMap<>();
    // 根节点在第一层
    nodeMap.put(root,1);
    // 当前层的节点数
    int curLevelNodeCnt = 0;
    // 当前所在的层
    int curLevel = 1;
    // 最大的节点个数
    int maxNodeCnt = -1;
    while (!queue.isEmpty()){
         root = queue.poll();
         // 还在当前层
         if (nodeMap.get(root) == curLevel){
             // 当前层的节点个数加1
             curLevelNodeCnt ++;
         } else { // 来到了下一层
             // 求最大的节点个数
             maxNodeCnt = Math.max(curLevelNodeCnt,maxNodeCnt);
             // 当前来到下一层 当前层的节点个数为 1
             curLevelNodeCnt = 1;
             curLevel ++;
         }
         if (root.left != null) {
             // 节点所在的层
             nodeMap.put(root.left,curLevel + 1);
             queue.add(root.left);
         }
         if (root.right != null){
             nodeMap.put(root.right,curLevel + 1);
             queue.add(root.right);
         }
    }
    return maxNodeCnt;
}

不使用hashMap求二叉树的最大宽度
使用两个变量当前层的结束节点 curEndNode 下一层的结束节点 nextEndNode
整个过程如图所示 :
在这里插入图片描述

coding

public static int getMaxWidthNoMap(TreeNode root){
      if (root == null){
          return 0;
      }
      Queue<TreeNode> queue = new LinkedList<>();
      queue.add(root);
      TreeNode curEndNode = root;//当前层的最后一个节点
      TreeNode nextEndNode = null;// 下一层的最后一个节点
      int curLevelNodeCnt = 1;
      int maxNodeCnt = -1;
      while (!queue.isEmpty()){
          TreeNode cur = queue.poll();
          if (cur.left != null){
              queue.add(cur.left);
              nextEndNode = cur.left;
          }

          if (cur.right != null){
              queue.add(cur.right);
              nextEndNode = cur.right;
          }

          // 当前节点是最后一个节点
          if (cur == curEndNode){
              maxNodeCnt = Math.max(curLevelNodeCnt,maxNodeCnt);
              curEndNode = nextEndNode;
              nextEndNode = null;
              // 要把当前层的最后一个节点算上 所以 curLevelNodeCnt置1
              curLevelNodeCnt = 1;
          } else { // 不是最后一个节点
              curLevelNodeCnt ++;
          }
      }
      return maxNodeCnt;
  }

6 判断一棵二叉树是否是搜索二叉树

使用中序遍历的方式判断

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
  /**
   * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
   *
   *
   * @param root TreeNode类
   * @return bool布尔型
   */
  public static int preVal = Integer.MIN_VALUE;
  public boolean isValidBST (TreeNode root) {
    // write code here
    if (root == null) {
      return true;
    }

    boolean isLeftBst = isValidBST(root.left);
    // 左边不是搜索二叉树  直接返回
    if (!isLeftBst) {
      return false;
    }

    if (root.val <= preVal) {
      return false;
    } else {
      preVal = root.val;
    }
    return isValidBST(root.right);
  }
}


使用非递归方式进行判断

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
  /**
   * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
   *
   *
   * @param root TreeNode类
   * @return bool布尔型
   */
  public boolean isValidBST (TreeNode root) {
    // write code here
    if (root == null) {
      return true;
    }
    Stack<TreeNode> stack = new Stack<>();
    int preVal = Integer.MIN_VALUE;
    while (!stack.isEmpty() || root != null ) {
      //左边进栈
      if (root != null) {
        stack.push(root);
        root = root.left;
      } else { // 弹出节点 右边界进栈
        root = stack.pop();
        if (root.val <= preVal) {
          return false;
        } else {
          preVal = root.val;
        }
        root = root.right;
      }
    }
    return true;
  }
}

使用递归套路求判断二叉树是否是搜索二叉树

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
  /**
   * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
   *
   *
   * @param root TreeNode类
   * @return bool布尔型
   */
  public class ReturnData {
    public boolean isBST;
    public int min;
    public int max;

    public ReturnData( boolean isBST, int min, int max) {
      this.isBST = isBST;
      this.min = min;
      this.max = max;
    }
  }
  public boolean isValidBST (TreeNode root) {
    // write code here
    return process(root).isBST;
  }

  public ReturnData process(TreeNode root) {
    if (root == null) {
      return null;
    }
    // 获取左侧数据 
    ReturnData leftData = process(root.left);
    // 获取右侧数据
    ReturnData rightData = process(root.right);

    boolean isBST = true;
    int min  = root.val;
    int max = root.val;

    if (leftData != null) {
      min = Math.min(leftData.min, min);
      max = Math.max(leftData.max, max);
      // 左侧已经不是二叉树  或者左子树的最大值大于等于当前节点的值 则不是搜素二叉树
      if (!leftData.isBST || (leftData.max >= root.val)) {
        isBST  = false;
      }
    }

    if (rightData != null) {
      min = Math.min(rightData.min, min);
      max = Math.max(rightData.max, max);
      if (! rightData.isBST || (rightData.min <= root.val)) {
        isBST = false;
      }
    }
    return new ReturnData(isBST,min,max);
  }
}

7 判断一棵二叉树是否是完全二叉树

关于什么是完全二叉树可以看博主文章
数据结构与算法之排序算法 堆排序节

如下所示的二叉树就是完全二叉树
在这里插入图片描述

使用宽度优先进行遍历,在遍历的过程中如果遇到如下情况 :

  1. 有右子节点,但是没有左子节点 直接返回false
  2. 在1)不违规的条件下,如果遇到了左右子节点不双全的情况,接下来的所有节点必须是叶子节点,否则就不是完全为二叉树
import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
  /**
   * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
   *
   *
   * @param root TreeNode类
   * @return bool布尔型
   */
  public boolean isCompleteTree (TreeNode root) {
    // write code here
    if (root == null) {
      return true;
    }
    Queue<TreeNode> queue = new LinkedList<>();
    queue.add(root);
    boolean isLeaf = false;
    while (!queue.isEmpty()) {
      TreeNode cur = queue.poll();
      TreeNode left = cur.left;
      TreeNode right = cur.right;
      // 当前节点有右子节点 但是没有左子节点
      if (left == null && right != null) {
        return false;
      }
      
      // 如果已经遇到了叶子节点 后面还是出现了非叶子节点 则不是完全二叉树
      if (isLeaf && (left != null || right != null)) {
        return false;
      }

      // 如果之前没有遇到过叶子节点  需要判断一下当前节点是否只有一个节点 
      // 如果只有一个 则是叶子节点
      if (!isLeaf && (left == null || right == null)) {
        isLeaf = true;
      } 

      if (left != null) {
        queue.add(left);
      }

      if (right != null) {
        queue.add(right);
      }
    }
    return true;
  }
}

8 判断一棵树是否是满二叉树


二叉树的节点个数n和二叉树h的高度满足如下关系 :

     n = 2 h − 1 n = 2 ^ h - 1 n=2h1

coding

public static class Info{
   int height;
   int nodesCount;

   public Info (int height,int nodesCount){
       this.height = height;
       this.nodesCount = nodesCount;
   }
}

public static boolean isFullTree(TreeNode root){
   Info info = process(root);
   // 二叉树节点的个数与 二叉树的高度满足关系 N = 2^h - 1
   return info.nodesCount == 1 << info.height - 1;
}

public static Info process(TreeNode root){
   if (root == null){
       return new Info(0,0);
   }
   Info leftInfo = process(root.left);
   Info rightInfo = process(root.right);
   int height = Math.max(leftInfo.height,rightInfo.height) + 1;
   int nodesCount = leftInfo.nodesCount + rightInfo.nodesCount + 1;
   return new Info(height,nodesCount);
}

9 判断一棵二叉树是否是平衡二叉树

平衡二叉树: 左树和右树的高度差不超过1

leetcode题目
描述
输入一棵节点数为 n 二叉树,判断该二叉树是否是平衡二叉树。
在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树
平衡二叉树(Balanced Binary Tree),具有以下性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。

/**
  * 判断一棵树是否是平衡二叉树
  * @param root
  * @return
  */
 public static boolean isBalanceTree(TreeNode root){
     return process(root).isBalance;
 }

 public static ReturnData process(TreeNode root){
     if (root == null){
         return new ReturnData(true,0);
     }
     // 左树返回数据 : 左树的高度 左树是否是平衡二叉树
     ReturnData leftData = process(root.left);
     // 右树返回数据 : 右树的高度  右树是否是平衡二叉树
     ReturnData rightData = process(root.right);
     int height = Math.max(leftData.height,rightData.height) + 1;
     boolean isBalance = leftData.isBalance && rightData.isBalance &&
             Math.abs(leftData.height - rightData.height) < 2;
     return new ReturnData(isBalance,height);
 }

 public static class ReturnData{
     public boolean isBalance;//是否是平衡二叉树
     public int height;//树的高度
     public ReturnData(boolean isBalance,int height){
         this.isBalance = isBalance;
         this.height = height;
     }
 }

10 公共祖先问题

给定两个二叉树的节点node1node2,找到他们的最低公共祖先节点

在这里插入图片描述

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
  /**
   * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
   *
   *
   * @param root TreeNode类
   * @param p int整型
   * @param q int整型
   * @return int整型
   */

  public int lowestCommonAncestor (TreeNode root, int p, int q) {
    // write code here
    // 每个节点的及其父节点放在Map中
    // key 每个节点 value 每个节点的父节点
    Map<Integer, Integer> parentMap = new HashMap<>();
    parentMap.put(root.val, root.val);
    process(root, parentMap);
    Set<Map.Entry<Integer, Integer>> entries = parentMap.entrySet();
    for (Map.Entry<Integer, Integer> entry : entries) {
      System.out.println(entry.getKey() + " : " + entry.getValue());
    }
    Set<Integer> set = new HashSet<>();
    set.add(root.val);
    int cur1 = p;
    int cur2 = q;
    // n1一直往上蹿
    while (cur1 != parentMap.get(cur1)) {
      set.add(cur1);
      cur1 = parentMap.get(cur1);
    }

    while (cur2 != parentMap.get(cur2)) {
      if (set.contains(cur2)) {
        return cur2;
      }
      cur2 = parentMap.get(cur2);
    }
    return root.val;
  }

  /**
     * 设置每个节点及其父节点进 HashMap
     * @param root
     * @param parentMap
     */
  public static void process(TreeNode root, Map<Integer, Integer> parentMap) {
    if (root == null) {
      return;
    }
    if (root.right != null) {
      parentMap.put(root.right.val, root.val);
    }
    if (root.left != null) {
      parentMap.put(root.left.val, root.val);
    }
    process(root.left, parentMap);
    process(root.right, parentMap);
  }
}

 

11 二叉树的层序遍历

 
给定一个二叉树,返回该二叉树层序遍历的结果,(从左到右,一层一层地遍历)

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
  /**
   * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
   *
   *
   * @param root TreeNode类
   * @return int整型ArrayList<ArrayList<>>
   */
  public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) {
    // write code here
    ArrayList<ArrayList<Integer>> arrayLists = new ArrayList<>();
    if (root == null) {
      return arrayLists;
    }
    Queue<TreeNode> queue = new LinkedList<>();
    queue.add(root);
    while (!queue.isEmpty()) {
      ArrayList<Integer> list = new ArrayList<>();
      // 当前层的节点个数
      int count =  queue.size();
      // 会把下一层的所有元素都放在队列中
      while (count-- > 0) {
        TreeNode node = queue.poll();
        list.add(node.val);
        if (node.left != null) {
          queue.add(node.left);
        }
        if (node.right != null) {
          queue.add(node.right);
        }
      }
      arrayLists.add(list);
    }
    return arrayLists;
  }
}

 


 

12 C++ 版本二叉树相关算法

 

#include <iostream>
#include <stack>
#include <list>
#include <vector>
#include <queue>

using namespace std;
#ifndef __BINARYTREE_H__
#define __BINARYTREE_H__
template <typename T>
struct STreeNode
{
    STreeNode() {}
    STreeNode(const T &data) : m_data(data), m_leftNode(NULL), m_rightNode(NULL)
    {
    }
    T m_data;
    STreeNode *m_leftNode;  // 左子节点
    STreeNode *m_rightNode; // 右子节点
    friend ostream &operator<<(ostream &os, const STreeNode &node)
    {
        return os << node.m_data;
    }
};

/**
 * @brief  在树中插入节点  树是平衡二叉树 即对于树的每个节点而言
 *  其左子树的每个值都比它小 右子树上的值不小于它
 *
 * @tparam T
 * @param root 树根  注意 这个地方要地址的引用
 * @param value
 */
template <typename T>
void insertNode(STreeNode<T> *&root, T value)
{
    // 创建节点
    STreeNode<T> *node = new STreeNode<T>(value);
    if (root == NULL)
    {
        root = node;
    }
    else
    {
        STreeNode<T> *tmpNode = root;
        while (tmpNode)
        {
            if (value < tmpNode->m_data) // 插入左子树
            {
                if (tmpNode->m_leftNode == NULL)
                {
                    tmpNode->m_leftNode = node;
                    return;
                }
                else
                {
                    tmpNode = tmpNode->m_leftNode;
                }
            }
            else // 插入右子树
            {
                if (tmpNode->m_rightNode == NULL)
                {
                    tmpNode->m_rightNode = node;
                    return;
                }
                else
                {
                    tmpNode = tmpNode->m_rightNode;
                }
            }
        }
    }
}

/**
 * @brief 二叉树的中序遍历
 *
 *
 * @tparam T
 * @param root
 */
template <typename T>
void inOrder_Traversal(STreeNode<T> *root)
{
    if (!root)
    {
        return;
    }
    inOrder_Traversal(root->m_leftNode);
    std::cout << *root << " ";
    inOrder_Traversal(root->m_rightNode);
}

/**
 * @brief  二叉树的前序遍历
 *
 * @tparam T
 * @param root
 */
template <typename T>
void preOrder_Traversal(STreeNode<T> *root)
{
    if (root == NULL)
    {
        return;
    }
    std::cout << *root << " ";
    preOrder_Traversal(root->m_leftNode);
    preOrder_Traversal(root->m_rightNode);
}

/**
 * @brief 二叉树的后序遍历
 *
 * @tparam T
 * @param root
 */
template <typename T>
void postOrder_Traversal(STreeNode<T> *root)
{
    if (root == NULL)
    {
        return;
    }
    postOrder_Traversal(root->m_leftNode);
    postOrder_Traversal(root->m_rightNode);
    std::cout << *root << " ";
}

/**
 * @brief 二叉树的非递归前序遍历
 *
 *
 * @tparam T
 * @param root
 */
template <typename T>
void preOrder_traversalNoRecurr(STreeNode<T> *root)
{
    if (!root)
    {
        return;
    }

    stack<STreeNode<T> *> s;
    s.push(root);
    while (!s.empty())
    {
        root = s.top();
        std::cout << *root << " ";
        s.pop();
        if (root->m_rightNode)
        {
            s.push(root->m_rightNode);
        }
        if (root->m_leftNode)
        {
            s.push(root->m_leftNode);
        }
    }
}

/**
 * @brief 二叉树中序遍历 非递归方式
 *
 * @tparam T
 * @param root
 */
template <typename T>
void inOrder_travelsalNonRecurr(STreeNode<T> *root)
{
    if (!root)
    {
        return;
    }
    stack<STreeNode<T> *> stack;

    while (stack.empty() == false || root != NULL)
    {
        /* 左子节点不为空 则一直入栈 */
        if (root)
        {
            stack.push(root);
            root = root->m_leftNode;
        }
        /* 左子节点为空  则弹出一个 往右子树上遍历 */
        else
        {
            root = stack.top();
            std::cout << *root << " ";
            stack.pop();
            root = root->m_rightNode;
        }
    }
    std::cout << "\n";
}

/**
 * @brief  二叉树后序遍历 非递归方式
 *
 *
 * @tparam T
 * @param root
 */
template <typename T>
void postOrder_traversalNonRecurr(STreeNode<T> *root)
{
    if (!root)
    {
        return;
    }

    stack<STreeNode<T> *> s1;
    stack<STreeNode<T> *> s2;
    s1.push(root);

    while (!s1.empty())
    {
        root = s1.top();
        s2.push(root);
        s1.pop();
        if (root->m_leftNode)
        {
            s1.push(root->m_leftNode);
        }
        if (root->m_rightNode)
        {
            s1.push(root->m_rightNode);
        }
    }

    while (!s2.empty())
    {
        root = s2.top();
        std::cout << *root << " ";
        s2.pop();
    }
    std::cout << "\n";
}

/**
 * @brief 二叉树宽度优先遍历
 * 
 * @tparam T 
 * @param root 
 */
template <typename T>
void widthFirstTraversal(STreeNode<T> *root)
{
    if (!root)
    {
        return;
    }
    list<STreeNode<T> *> queue;
    queue.push_back(root);
    while (!queue.empty())
    {
        root = queue.front();
        std::cout << *root << " ";
        queue.pop_front();

        if (root->m_leftNode)
        {
            queue.push_back(root->m_leftNode);
        }
        if (root->m_rightNode)
        {
            queue.push_back(root->m_rightNode);
        }
    }
    std::cout << "\n";
}

/**
 * @brief 二叉树的层序遍历
 *
 *
 * @tparam T
 * @param root
 * @return std::vector<std::vector<STreeNode<T>*>>
 */
template <typename T>
std::vector<std::vector<STreeNode<T> *>> levelOroder(STreeNode<T> *root)
{
    std::vector<std::vector<STreeNode<T> *>> vecRet;
    vecRet.clear();
    if (root)
    {
        std::queue<STreeNode<T> *> queue;
        queue.push(root);
        while (!queue.empty())
        {
            std::vector<STreeNode<T> *> vecTreeNode;
            vecTreeNode.clear();
            int count = queue.size();
            // 遍历一层  将下一层的节点放入队列
            while (count--)
            {
                root = queue.front();
                vecTreeNode.push_back(root);
                queue.pop();
                if (root->m_leftNode)
                {
                    queue.push(root->m_leftNode);
                }
                if (root->m_rightNode)
                {
                    queue.push(root->m_rightNode);
                }
            }
            vecRet.push_back(vecTreeNode);
        }
        return vecRet;
    }
    return vecRet;
}

/**
 * @brief 销毁二叉树
 *
 * @tparam T
 * @param root
 */
template <typename T>
void destroy_Tree(STreeNode<T> *&root)
{
    if (root == NULL)
    {
        return;
    }
    destroy_Tree<T>(root->m_leftNode);
    destroy_Tree<T>(root->m_rightNode);
    if (root != NULL)
    {
        std::cout << "<<< destroy[" << root << "]\n";
        delete root;
        root = NULL;
    }
}

/******************************************************************************************/
#include "BinaryTreeTest.h"
#include <iostream>
#include "BinaryTree.h"
void test_insertNode()
{
    STreeNode<int32_t> *root = NULL;

    // 构建一棵二叉树
    for (int32_t data : {10, 12, 5, 2, 1})
    {
        insertNode<int32_t>(root, data);
    }

    std::cout << "\n ---------------------preOrder_traversalNoRecurr---------------------\n";
    preOrder_traversalNoRecurr(root);

    std::cout << "\n ---------------------inOrder_travelsalNonRecurr---------------------\n";
    inOrder_travelsalNonRecurr(root);

    std::cout << "\n ---------------------postOrder_traversalNonRecurr---------------------\n";
    postOrder_traversalNonRecurr(root);
    std::cout << "\n";

    std::cout << "\n ---------------------widthFirstTraversal---------------------\n";
    widthFirstTraversal(root);

    destroy_Tree(root);
}

int test_levelOroder()
{
    STreeNode<int32_t> *root = NULL;

    // 构建一棵二叉树
    for (int32_t data : {10, 12, 5, 2, 1,12,14,20,90,45,89,10,12,89})
    {
        insertNode<int32_t>(root, data);
    }

    std::vector<vector<STreeNode<int32_t> *>> vecRet =
        levelOroder(root);

    std::vector<vector<STreeNode<int32_t> *>>::const_iterator iter = vecRet.begin();
    for (; iter != vecRet.end();++iter)
    {
        std::vector<STreeNode<int32_t> *>::const_iterator streeNodeIter = (*iter).begin();
        for (; streeNodeIter != (*iter).end();++streeNodeIter)
        {
            std::cout << *(*streeNodeIter) << " ";
        }
        std::cout << "\n";
    }
    std::cout << "\n";

    destroy_Tree(root);

    return 0;
}


/******************************************************************************************/

#endif // __BINARYTREE_H__
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值