Leetcode 已知前序(後序)遍歷和中序遍歷構建二叉樹
阿新 • • 發佈:2018-12-24
我們知道,中序遍歷是左子樹->根節點->右子樹。因此我們可以通過中序遍歷可以確定左右子樹的元素個數。
而通過前序(後序)遍歷,我們可以確定根節點的位置,然後通過尋找根節點在中序遍歷的位置,可以確定左右子樹。
然後遞迴遞迴左右子樹實現構建二叉樹。
前序和中序:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode buildTree(int[] preorder, int[] inorder) { if(preorder==null&&inorder==null) return null; return rebuild (preorder,inorder,0,preorder.length-1,0,inorder.length-1); } private TreeNode rebuild(int[] preorder, int[] inorder,int preleft,int preright,int inleft,int inright) { if(preleft>preright||inleft>inright) return null; TreeNode t=new TreeNode(preorder[preleft]); t.left=t.right=null; int loc=0; //尋找節點在中序遍歷中的位置 for (int i=inleft;i<=inright;i++) if(inorder[i]==preorder[preleft]) { loc=i; break; } //preleft+1表示該節點的左孩子的位置,preleft+loc-inleft表示該節點左子樹的末尾 t.left=rebuild (preorder,inorder,preleft+1,preleft+loc-inleft,inleft,loc-1); //preleft+loc-inleft+1表示該節點的右孩子的位置,preright表示該節點右子樹的末尾 t.right=rebuild (preorder,inorder,preleft+loc-inleft+1,preright,loc+1,inright); return t; } }
後序和中序:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode buildTree(int[] inorder, int[] postorder) { if(inorder==null&&postorder==null) return null; return rebuild (inorder,postorder,0,postorder.length-1,0,inorder.length-1); } private TreeNode rebuild(int[] in, int[] post,int postleft,int postright,int inleft,int inright) { if(postleft>postright||inleft>inright) return null; int loc=-1; TreeNode t=new TreeNode(post[postright]); t.left=t.right=null; for (int i=inleft;i<=inright;i++) if(in[i]==post[postright]) { loc=i; break; } //postright-inright+loc-1表示該節點左孩子的位置,posleft表示左子樹的起始 t.left=rebuild (in,post,postleft,postright-inright+loc-1,inleft,loc-1); //postright-1表示該節點右孩子的位置,postright-inright+loc表示右子樹的起始 t.right=rebuild(in,post,postright-inright+loc,postright-1,loc+1,inright); return t; } }