zoukankan      html  css  js  c++  java
  • 二叉树 根据后序遍历生成二叉树

    题目:给定一个二叉树的后序遍历数组arr[],生成二叉树

    解题思路:根据搜索二叉树的性质,数组的最后一位arr[end]是二叉树的根,而且数组的左部分比arr[end]小,是根节点的左子数,数字的右部分比arr[end]大,是数组的右子数。

    Example:

    树的形状如上图,后序遍历为:1 3 2 6  8 7 5

    arr[end] = 5;

    左部分(左子树):{1,3,2}

    右部分(右子树):{6,8,7}

    package cn.edu.algorithm.prototype;
    
    /**
     * 根据后序遍历构造二叉树
     */
    public class Main {
        public static void main(String[] args) {
            int[] arr = {1, 3, 2, 6, 8, 7, 5};
            TreeNode root = postToBST(arr, 0, arr.length - 1);
            inOrder(root);
        }
        public static void inOrder(TreeNode node) {
    
            if (node != null) {
                inOrder(node.left);
                System.out.println(node.value);
                inOrder(node.right);
            }
        }
        public static TreeNode postToBST(int[] arr, int start, int end) {
            if (start > end)
                return null;
            TreeNode node = new TreeNode(arr[end]);
            int less = -1;
            int more = end;
            for (int i = start; i < end; i++) {
                if (arr[end] > arr[i]) {
                    less = i;
                } else {
                    more = more == end ? i : more;
                }
            }
            node.left = postToBST(arr, start, less);
            node.right = postToBST(arr, more, end - 1);
            return node;
        }
    }
    class TreeNode {
        protected int value;
        protected TreeNode left;
        protected TreeNode right;
    
        public TreeNode(int value) {
            this.value = value;
        }
    }
  • 相关阅读:
    垂直水平居中几种实现风格
    重绘(repaint)和回流(reflow)
    对象深拷贝
    PhantomJS not found on PATH
    d3.js 数据操作
    canvas 绘制圆弧
    d3.js 柱状图
    d3.js -- 比例尺 scales scaleLinear scaleBand scaleOrdinal scaleTime scaleQuantize
    d3.js -- select、selectAll
    map映射
  • 原文地址:https://www.cnblogs.com/googlemeoften/p/5852311.html
Copyright © 2011-2022 走看看