leetcode:Populating Next Right Pointers in Each Node

来源:互联网 发布:国产psp4000淘宝 编辑:程序博客网 时间:2024/06/07 17:51

题目

Populating Next Right Pointers in Each Node
Given a binary tree

struct TreeLinkNode {  TreeLinkNode *left;  TreeLinkNode *right;  TreeLinkNode *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.

Note:

You may only use constant extra space.
You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
For example,
Given the following perfect binary tree,

         1       /  \      2    3     / \  / \    4  5  6  7

After calling your function, the tree should look like:

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

思路

注意,题目说了是一个assume that it is a perfect binary tree,所以,每一层左侧一定不为空

我的解法

我采用层次遍历的方法,用一个队列保存节点;每进入一个节点,就将队尾的节点的next域指向它。这样每个节点的next都有对象,与最终结果不符。然后再从根结点依次遍历右子树,并将右孩子的next域置为null,得到结果。

/** * 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) {        Queue<TreeLinkNode> queue = new LinkedList<TreeLinkNode>();        TreeLinkNode node = root;        TreeLinkNode pre = root;        if (node != null)            queue.add(node);        while (queue.peek() != null) {            node = queue.poll();            if (node.left != null) {                pre.next = node.left;                pre = node.left;                queue.add(node.left);            }            if (node.right != null) {                pre.next = node.right;                pre = node.right;                queue.add(node.right);            }        }        node = root;        while (node != null) {            node.next = null;            node = node.right;        }    }}

优化

层次遍历的思想,每层遍历都从最左节点开始,然后通过next依次向右访问节点。访问到的节点,设置自己左右孩子的next域

public class Solution {    public void connect(TreeLinkNode root) {        while (root != null) {            TreeLinkNode node = root;            while (node != null && node.left != null) {                node.left.next = node.right;                if (node.next != null) {                    node.right.next = node.next.left;                }                node = node.next;            }            root = root.left;        }    }}
0 0
原创粉丝点击