116. Populating Next Right Pointers in Each Node

Solution: Iterative 每层遍历,对应连接

思路:Because the input is a perfect binary tree that has complete nodes, the following idea for every level would work:

屏幕快照 2017-09-06 下午7.06.11.png

Time Complexity:O(N) Space Complexity: O(1)

Solution2:dfs 自round1

Time Complexity:O(N) Space Complexity: O(logN) 递归缓存

Solution Code:

public class Solution {
    public void connect(TreeLinkNode root) {
        TreeLinkNode level_head = root;
        while (level_head != null) {
            TreeLinkNode cur = level_head;
            while (cur != null) {
                if (cur.left != null) cur.left.next = cur.right;
                if (cur.right != null && cur.next != null) cur.right.next = cur.next.left;
                cur = cur.next;
            }
            level_head = level_head.left;
        }
    }
}
public class Solution {
    public void connect(TreeLinkNode root) {
        dfs(root);
    }
    
    private void dfs(TreeLinkNode root) {
        if(root == null || root.left == null || root.right == null) return;
        
        root.left.next = root.right;
        if(root.next != null) {
            root.right.next = root.next.left;
        }
        
        dfs(root.left);
        dfs(root.right);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容