树相关操作

119 阅读1分钟

求树的高度

// leetcode 104
// 深度优先
public int maxDepth(TreeNode root) {
        if(root==null){
            return 0;
        }

        int left = maxDepth(root.left);
        int right = maxDepth(root.right);
        return Math.max(left, right) + 1;
        
 }

//广度优先
public int maxDepth(TreeNode root) {
        
        if(root == null){
            return 0;
        }
     
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int result = 0;
        while(!queue.isEmpty()){
            int size = queue.size();
            while(size>0){
                TreeNode node = queue.poll();
                if(node.left!=null){
                    queue.offer(node.left);
                }
                if(node.right!=null){
                    queue.offer(node.right);
                }
                size--;
            }
            result++;
        }
        return result;
}

判断是否为平衡二叉树

//leetcode 110
//自顶向下 
class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root == null){
            return true;
        }
        return Math.abs(tree_hight(root.left)-tree_hight(root.right))<=1 
                && isBalanced(root.left) && isBalanced(root.right);

    }

    public int tree_hight(TreeNode root){

        int high = 0;
        if(root == null){
            return high;
        }
        int left = tree_hight(root.left);
        int right = tree_hight(root.right);
        return Math.max(left,right)+1;
    }
}

//自底向上 类似于后序遍历,对于当前遍历到的节点,先递归地判断其左右子树是否平衡,
//再判断以当前节点为根的子树是否平衡。如果一棵子树是平衡的,则返回其高度(高度一定是非负整数),
//否则返回 -1−1。如果存在一棵子树不平衡,则整个二叉树一定不平衡

class Solution {    public boolean isBalanced(TreeNode root) {       return tree_hight(root) >= 0;    }    public int tree_hight(TreeNode root){        int high = 0;        if(root == null){            return high;        }        int left = tree_hight(root.left);        int right = tree_hight(root.right);        if(left==-1 || right==-1 || Math.abs(left-right)>1){            return -1;        }        return Math.max(left,right)+1;    }}

求二叉树的最大路径和

// leetcode:124

class Solution {
    int max_value = Integer.MIN_VALUE;

    public int maxPathSum(TreeNode root) {
        maxGain(root);
        return max_value;

    }

    public int maxGain(TreeNode node){
        if(node==null){
            return 0;
        }
        int left = Math.max(maxGain(node.left),0);
        int right = Math.max(maxGain(node.right),0);
        int max_path = node.val + left + right;
        if(max_value<max_path){
            max_value = max_path;
        } 
        return node.val + Math.max(left, right);  
    }
}

求最近祖先

//leetcode:236
//方法一:递归
class Solution {

    TreeNode result = null;
    
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        dfs(root, p , q);
        return result;
    }

    public boolean dfs(TreeNode node,TreeNode p, TreeNode q ){
        if(node == null){
            return false;
        }
        boolean left = dfs(node.left, p, q);
        boolean right = dfs(node.right, p, q);
        if((left&&right)||((node==p||node==q)&&(left||right))){
            result = node;
        }
        return left||right||node==p || node==q; 
    }
}

//方法二:递归二
class Solution {    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {       if(root==null || root==p || root==q){           return root;       }       TreeNode left = lowestCommonAncestor(root.left, p, q);       TreeNode right = lowestCommonAncestor(root.right, p, q);       if(left == null && right == null){           return null;       }       if(left == null){           return right;       }       if(right == null){           return left;       }       // p 和 q 分别在left 和 right 两边       return root;    }}
//方法三:记录父节点,再遍历寻找公共节点
class Solution {

    Map<Integer, TreeNode> parents = new HashMap<>();
    List<Integer> visit = new ArrayList<Integer>();

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        dfs(root);
        while(p!=null){
            visit.add(p.val);
            TreeNode parent = parents.get(p.val);
            p = parent;
        }
        while(q!=null){
            if(visit.contains(q.val)){
                return q;
            }
            TreeNode parent = parents.get(q.val);
            q = parent;
        }
        return null;
    }

    public void dfs(TreeNode node){
       if(node.left!=null){
           parents.put(node.left.val, node);
           dfs(node.left);
       }
       
       if(node.right!=null){
           parents.put(node.right.val, node);
           dfs(node.right);
       }
    }
}

验证二叉搜索树

leetcode 98
//方法一:递归
class Solution {    
    public boolean isValidBST(TreeNode root) {       
        return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);    
    }    

    public boolean isValidBST(TreeNode node, long low, long high){        
        if(node == null){            
            return true;        
        }        
        if(node.val<=low || node.val>=high){            
            return false;        
        }        
        return isValidBST(node.left, low, node.val) && isValidBST(node.right, node.val, high);    
    }
}

//方法二:中序遍历
class Solution {    
    public boolean isValidBST(TreeNode root) {        
        if(root == null){            
            return true;        
        }        
        Deque<TreeNode> deque = new LinkedList<>();        
        long pre = Long.MIN_VALUE;        
        while(!deque.isEmpty()||root!=null){            
            while(root!=null){                
                deque.push(root);                
                root = root.left;            
            }            
            root = deque.pop();            
            if(root.val <= pre){                
                return false;            
            }            
            pre = root.val;            
            root = root.right;        
        }       return true;    
    }   
}

二叉搜索数的插入

//leetcode:701
class Solution {    
    public TreeNode insertIntoBST(TreeNode root, int val) {        
        TreeNode insert_node = new TreeNode(val, null, null);        
        if(root == null){            
            return insert_node;        
        }        
        TreeNode cur = root;        
        while(cur != null){            
            if(cur.val>val){                
                if(cur.left==null){                    
                    cur.left = insert_node;                    
                    break;                
                }else{                    
                    cur = cur.left;                
                }            
            }else{                
                if(cur.right == null){                    
                    cur.right = insert_node;                    
                    break;                
                }else{                    
                    cur = cur.right;                
                }            
            }        
        }        
        return root;            
    }
}