Construction of the binary tree 1008 preorder

Body intended to consolidate the construction of binary understanding preorder, concepts and binary search tree to problem-solving
(speed beat 100% java, memory only beat 5%)

/** * Definition for a binary tree node. 
* public class TreeNode { 
* *     int val;
*  *     TreeNode left; 
* *     TreeNode right; 
* *     TreeNode(int x) { val = x; } 
* * } 
* */
 class Solution {    
private TreeNode root = new TreeNode(0);    
public TreeNode bstFromPreorder(int[] preorder) {        
if(preorder.length==0) return null;       
 root = new TreeNode(preorder[0]);       
for(int i=1;i<preorder.length;i++)           
fun(preorder,i);       
return root;   
}    
public void fun(int[] preorder, int num){        
int a = preorder[num];        
TreeNode pos = root;        
while(true){
            if(pos.val>a){
                 if(pos.left==null) {pos.left = new TreeNodw(a);break;}
                 else {pos = pos.left;continue;}            
}
            else{
                if(pos.right==null) {pos.right = new TreeNode(a);break;}
                else {pos = pos.right;continue;}            
                }
             }    
}}

Published 26 original articles · won praise 2 · Views 711

Guess you like

Origin blog.csdn.net/qq_44028171/article/details/104254471