LeetCode 117 Populating Next Right Pointers in Each Node II (链表 层次遍历 推荐)

来源:互联网 发布:淘宝客app制作 编辑:程序博客网 时间:2024/06/16 01:53

Follow up for problem "Populating Next Right Pointers in Each Node".

What if the given tree could be any binary tree? Would your previous solution still work?

Note:

  • You may only use constant extra space.

For example,
Given the following binary tree,

         1       /  \      2    3     / \    \    4   5    7

After calling your function, the tree should look like:

         1 -> NULL       /  \      2 -> 3 -> NULL     / \    \    4-> 5 -> 7 -> NULL


题目链接:https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/

题目分析:和Populating Next Right Pointers in Each Node那题比本题不保证是满二叉树,因此如果用那题的做法将会非常麻烦,需要判断很多null的情况,换个角度思考,模拟一下树层次遍历的过程,给每一层加一个头结点,就可以解决这个问题。1ms

/** * Definition for binary tree with next pointer. * public class TreeLinkNode { *     int val; *     TreeLinkNode left, right, next; *     TreeLinkNode(int x) { val = x; } * } */public class Solution {    public void connect(TreeLinkNode root) {        TreeLinkNode lastNode = root;        while (lastNode != null) {            TreeLinkNode cur = new TreeLinkNode(0);            TreeLinkNode curHead = cur;            while (lastNode != null) {                if (lastNode.left != null) {                    cur.next = lastNode.left;                    cur = cur.next;                }                if (lastNode.right != null) {                    cur.next = lastNode.right;                    cur = cur.next;                }                lastNode = lastNode.next;            }            lastNode = curHead.next;        }    }}


0 0
原创粉丝点击