leetcode [117]Populating Next Right Pointers in Each Node II

Given a binary tree

struct Node {
  int val;
  Node *left;
  Node *right;
  Node *next;
}

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

Initially, all next pointers are set to NULL.

题目大意:

和leetcode[116]是一样的套路,只不过树给的不是完全二叉树。

解法:

这道题目采用之前的非递归算法,使用队列做https://www.cnblogs.com/xiaobaituyun/p/10705478.html

层次遍历非递归的java:

class Solution {
    public Node connect(Node root) {
        if(root==null) return root;
        Deque<Node>q=new LinkedList<>();
        q.add(root);
        while(!q.isEmpty()){
            int sz=q.size();
            for(int i=0;i<sz-1;i++){
                Node n=q.pop();
                n.next=q.peek();
                if(n.left!=null) q.add(n.left);
                if(n.right!=null) q.add(n.right);
            }
            Node n=q.pop();
            n.next=null;
            if(n.left!=null) q.add(n.left);
            if(n.right!=null) q.add(n.right);
        }
 
        return root;
    }
}

也可以按照递归的思路进行解题。

 java:

class Solution {
    private void connect(Node root,int h,List<List<Node>>list){
        if(root==null) return;
        if(h==list.size()) list.add(new ArrayList<>());
        if(list.get(h).size()>0) list.get(h).get(list.get(h).size()-1).next=root;
        list.get(h).add(root);
        connect(root.left,h+1,list);
        connect(root.right,h+1,list);
    }

    public Node connect(Node root) {
        connect(root,0,new ArrayList<>());
        return root;
    }
}

 

posted @ 2019-04-15 11:16  小白兔云  阅读(121)  评论(0编辑  收藏  举报