当前位置:   article > 正文

117. Populating Next Right Pointers in Each Node II(队列、二叉树)

117. Populating Next Right Pointers in Each Node II(队列、二叉树)
package Tree;

import java.util.LinkedList;
import java.util.Queue;

public class Connect_117 {
	class Node {
		public int val;
		public Node left;
		public Node right;
		public Node next;

		public Node() {
		}

		public Node(int _val) {
			val = _val;
		}

		public Node(int _val, Node _left, Node _right, Node _next) {
			val = _val;
			left = _left;
			right = _right;
			next = _next;
		}
	}

	public Node connect(Node root) {
		if(root==null) {
			return root;
		}
		// 每一行的节点用队列存储起来
		Queue<Node> queue = new LinkedList<>();
		queue.offer(root);
		while (!queue.isEmpty()) {
			Node pre = null;
			int size=queue.size();
			for (int i = 0; i < size; i++) {
				// 每一行串起来
				Node cur = queue.poll();
				if (i > 0) {
					pre.next = cur;
				}
				pre = cur;

				// 下一行存入队列
				if (cur.left != null) {
	                queue.offer(cur.left);
	            }
	            if (cur.right != null) {
	                queue.offer(cur.right);
	            }
			}

		}

		return root;

	}

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/290200?site
推荐阅读
相关标签
  

闽ICP备14008679号