美文网首页
2022-03-09 53,54二叉搜索树

2022-03-09 53,54二叉搜索树

作者: 16孙一凡通工 | 来源:发表于2022-03-09 10:57 被阅读0次

    展平二叉搜索树:
    java版本:

    class Solution {
         List<Integer> list=new ArrayList<Integer>();
        public TreeNode increasingBST(TreeNode root) {
    
            // 二叉树遍历
    
            DFS(root);
              TreeNode res=new TreeNode(list.get(0));
            TreeNode node=res;
           for(int i=1;i<list.size();i++){
                TreeNode temp=new TreeNode();
               temp.val=list.get(i);
               node.right=temp;
               node=node.right;
           }
    
           return res;
    
           
        }
        public void DFS(TreeNode root){
            if(root==null){
                return ;
            }
            DFS(root.left);
            list.add(root.val);
            DFS(root.right);
        
        }
    }
    

    二叉搜索树所有大于等于节点的和。

    class Solution {
        int count=0;
        
        public TreeNode convertBST(TreeNode root) {
            // 存起来排个序
            // 统计所有值之和
    //前两句的思路是错的
            // 直接遍历右边的统计值就行了
            TreeNode node=root;
           DFS(node);
           
            return node;
    
        }
        public void DFS(TreeNode root){
       if(root==null){
           return ;
       }
       DFS(root.right);
       count+=root.val;
       root.val=count;
       DFS(root.left);
        }
       
    }
    

    相关文章

      网友评论

          本文标题:2022-03-09 53,54二叉搜索树

          本文链接:https://www.haomeiwen.com/subject/wvqtdrtx.html