博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode - Populating Next Right Pointers in Each Node II
阅读量:4647 次
发布时间:2019-06-09

本文共 1312 字,大约阅读时间需要 4 分钟。

题目:

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

思路:

递归,对root的左右进行连接操作,然后先递归右树,再递归左树。

package tree;public class PopulatingNextRightPointersInEachNodeII {    public void connect(TreeLinkNode root) {        if (root == null || (root.left == null && root.right == null)) return;        TreeLinkNode next = root.next;        while (next != null) {            if(next.left != null) {                next = next.left;                break;            }                        if (next.right != null) {                next = next.right;                break;            }                        next = next.next;        }                if (root.right != null)             root.right.next = next;                 if (root.left != null)            root.left.next = root.right == null ? next : root.right;                        connect(root.right);        connect(root.left);    }}

 

转载于:https://www.cnblogs.com/null00/p/5127482.html

你可能感兴趣的文章
Network 第六篇 - 三层交换机配置路由功能
查看>>
OSL LLVM 3.3 Related Changes
查看>>
1.4 99乘法表
查看>>
雇佣K个工人的最小费用 Minimum Cost to Hire K Workers
查看>>
mysql优化方法
查看>>
[转]【HttpServlet】HttpServletResponse接口 案例:完成文件下载
查看>>
Eclipse配置默认的编码集为utf-8
查看>>
初学Python
查看>>
坑:Office Tool Plus在干啥呀
查看>>
[转]EXCEL截取字符串中某几位的函数——LeftMIDRight及Find函数的使用
查看>>
rman 脚本备份全过程
查看>>
图像处理笔记(十八):模板匹配
查看>>
Educational Codeforces Round 60 D. Magic Gems
查看>>
c# 保存和打开文件的方法
查看>>
调用图灵机器人API实现简单聊天
查看>>
MATLAB indexing question
查看>>
MATLAB 求解最优化问题
查看>>
【转载】java InputStream读取数据问题
查看>>
网络基础Cisco路由交换四
查看>>
CloudFoundry基础知识之理论篇
查看>>