LeetCode--257. Binary Tree Paths && 283. Move Zeroes

257. Binary Tree Paths
常用递归操作

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    public static List<String> list; 
    
    public List<String> binaryTreePaths(TreeNode root) {
        list=new LinkedList<>();
        if(root!=null)
            recursive(new StringBuilder(),root);
        return list;
    }
    
    public static void recursive(StringBuilder sb,TreeNode node){
        if(node.left==null && node.right==null){
            list.add(sb.append(node.val).toString());
            return;
        }
        sb.append(node.val);
        sb.append("->");
        if(node.left!=null){
            recursive(new StringBuilder(sb.toString()),node.left);
        }
        if(node.right!=null){
            recursive(new StringBuilder(sb.toString()),node.right);
        }
    } 
}

283. Move Zeroes

class Solution {
    public void moveZeroes(int[] nums) {
        int lastIndexNonZero=0,tmp=0;
        for(int i=0;i<nums.length;i++){
            if(nums[i]!=0)
            {
                tmp=nums[lastIndexNonZero];
                nums[lastIndexNonZero++]=nums[i];
                nums[i]=tmp;
            }
        }
    }
}

331. Verify Preorder Serialization of a Binary Tree

class Solution {
    public boolean isValidSerialization(String preorder) {
        
        String[] strs=preorder.split(",");
        int slot=1;
        for(int i=0;i<strs.length;i++){
            if(slot==0)
                return false;
            if(!strs[i].equals("#")){
                slot++;
            }
            else
                slot--;
        }
        return slot==0;
    }
}

猜你喜欢

转载自blog.csdn.net/To_be_to_thought/article/details/90141571