zoukankan      html  css  js  c++  java
  • 统计二叉树结点个数

    package com.basic.bt;

    import java.util.Stack;

    /**
    * 思路: 所谓计算个数,实际上是把每个结点遍历一遍
    * (1)递归
    * (2)非递归
    */
    public class CountNodes {

    int count = 0;
    //inorder
    public void countNodes(TreeNode root) {
    if(root == null) {
    return;
    }
    countNodes(root.left);
    count++;
    countNodes(root.right);
    }


    public void countPreOrder(TreeNode root) {
    if(root == null) {
    return;
    }
    Stack<TreeNode> stack = new Stack<TreeNode>();
    stack.push(root);
    //当最后一个节点出栈时,就是遍历结束的时候,所有while循环里面不用判断 root是否为空,且root指针从未改变过。 中序遍历时需要主要
    while(!stack.isEmpty()) {
    TreeNode tmp = stack.pop();
    count++;
    if(tmp.right != null) {
    stack.push(tmp.right);
    }
    if(tmp.left != null) {
    stack.push(tmp.left);
    }
    }
    }


    //
    public void countInOrder(TreeNode root) {
    if(root == null) {
    return;
    }
    Stack<TreeNode> stack = new Stack<TreeNode>();
    while(root != null || !stack.isEmpty()) {

    while(root != null) {
    stack.push(root);
    root = root.left;
    }
    TreeNode node = stack.peek();
    stack.pop();
    count++;
    root = node.right;
    }
    }

    public void countPostOrder(TreeNode root) {
    if(root == null) {
    return;
    }
    Stack<TreeNode> stack = new Stack<TreeNode>();
    TreeNode pre = null;
    TreeNode node = root;
    while(node != null || !stack.isEmpty()) {
    if(node != null) {
    stack.push(node);
    node = node.left;
    }
    node = stack.pop();
    count++;
    while(node!= null && (node.right == null || node.right == pre)) {
    count++;
    pre = node;
    //先判断是否为空,再pop 当只有最后一个节点的时候,本场景可以思考成功
    if(stack.isEmpty()) {
    return;
    }
    node = stack.pop();
    }
    count++;
    stack.push(node);
    node = node.right;
    }

    }

    public static void main(String[] args) {
    CountNodes test = new CountNodes();
    TreeNode root = new TreeNode(0);
    TreeNode node1 = new TreeNode(1);
    TreeNode node2 = new TreeNode(2);
    TreeNode node3 = new TreeNode(3);
    TreeNode node4 = new TreeNode(4);
    root.left = node1;
    root.right = node2;
    node1.left = node3;
    node1.right =node4;
    test.countPostOrder(root);
    System.out.println("二叉树的结点个数为:" + test.count);
    }
    }
  • 相关阅读:
    组合数学+结论——cf1359E
    【模拟】分类讨论大模拟+数论——cf1358F
    【思维】前缀和——cf1358E
    Android基础—— 自定义RecyclerView内部控件的监听器
    【思维】模拟+暴力——icpc nwrrc 2019 K
    分治模板
    树上问题&图论模板整理
    数据结构模板整理
    一些计数题
    Codeforces Round #567 (Div. 2)
  • 原文地址:https://www.cnblogs.com/superzhaochao/p/6337386.html
Copyright © 2011-2022 走看看