zoukankan      html  css  js  c++  java
  • Construct Binary Tree from Inorder and Postorder Traversal

    Construct Binary Tree from Inorder and Postorder Traversal

    问题:

      Given inorder and postorder traversal of a tree, construct the binary tree.

    思路:

      dfs

    我的代码:

    public class Solution {
        public TreeNode buildTree(int[] inorder, int[] postorder) {
            if(inorder == null || inorder.length == 0)  return null;
            if(inorder.length == 1) return new TreeNode(inorder[0]);
            int len = postorder.length;
            int target = postorder[len-1];
            int index = getIndex(inorder, target);
            TreeNode root = new TreeNode(target);
            root.left = buildTree(Arrays.copyOfRange(inorder,0,index),Arrays.copyOfRange(postorder,0,index));
            root.right = buildTree(Arrays.copyOfRange(inorder, index+1, len),Arrays.copyOfRange(postorder, index, len-1));
            return root;
        }
        public int getIndex(int[] inorder, int target)
        {
            for(int i = 0; i < inorder.length; i++)
            {
                if(inorder[i] == target)
                    return i;
            }
            return -1;
        }
    }
    View Code
  • 相关阅读:
    window.open
    GetPostBackClientHyperlink
    引发和使用事件
    浅谈宝宝的教育及培养
    C#关键字之:base、this
    Ioc
    自定义input[type="radio"]的样式
    选择_冒泡_直接插入排序.md
    Tkinter.md
    从零开始学wordpress 之一
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4335933.html
Copyright © 2011-2022 走看看