2022-02-28-03-01 二叉树最底层最左边的值+Z 字

2022-03-01  本文已影响0人  16孙一凡通工

剑指 Offer II 045. 二叉树最底层最左边的值

Go的可变数组的slice用的有bug,换java写队列

java版本:

class Solution {
    public int findBottomLeftValue(TreeNode root) {

    // ArrayDeque<TreeNode> queue=new ArrayDeque<>();
     Queue<TreeNode> queue=new LinkedList<>();
    queue.offer(root);
    int visited=root.val;
    int count=0;
    int m;

    while(queue.peek()!=null){
        count=0;
        m=queue.size();
        // 标志


        if(m==1){
            visited=queue.peek().val;
        }

       
        
        for(int i=0;i<m;i++){
           TreeNode node=queue.peek();
            
             queue.poll();
        //    System.out.print("node:"+node.val);
          if (node.left!=null){
              
              queue.offer(node.left);
          }
           if (node.left!=null && count==0) {
               visited=node.left.val;
               count++;
           }
          if(node.right!=null){
              queue.offer(node.right);
          }
        }
         System.out.println();

    }

    return visited;


    }
}

6. Z 字形变换

Go版本:

func convert(s string, numRows int) string {


    arr:=[]string{};
    for i:=0;i<numRows;i++{
        arr=append(arr,"")
    }

    p,n:=0,len(s);
    for p<n{
       for i:=0;i<numRows && p<n ;i++{
         
           arr[i]+=string(s[p])
             p++;
       }
        for i:=numRows-2;i>=1 && p<n ;i--{
           arr[i]+=string(s[p])
           p++; 
       }
    }
    res:=""

    for i:=0;i<numRows;i++{
   res+=arr[i]
    }
    return res;

}
上一篇下一篇

猜你喜欢

热点阅读