zoukankan      html  css  js  c++  java
  • leetcode-每个节点的右向指针(填充同一层的兄弟节点)

    给定一个二叉树

    struct TreeLinkNode {
      TreeLinkNode *left;
      TreeLinkNode *right;
      TreeLinkNode *next;
    }

    填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL

    初始状态下,所有 next 指针都被设置为 NULL

    说明:

    • 你只能使用额外常数空间。
    • 使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。
    • 你可以假设它是一个完美二叉树(即所有叶子节点都在同一层,每个父节点都有两个子节点)。

    示例:

    给定完美二叉树,

         1
       /  
      2    3
     /   / 
    4  5  6  7

    调用你的函数后,该完美二叉树变为:

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

    递归法:因为是完美二叉树,如果有左子树,一定有右子树。我们将结点的左子树和右子树相连。
    如果结点next不为空,那么将结点右子树指向结点next的左子树。
    同时递归处理左子树和右子树。
    public class Solution {
        public void connect(TreeLinkNode root) {
            if(root==null)return ;
            if(root.left!=null){
                root.left.next=root.right;
                if(root.next!=null)root.right.next=root.next.left;
            
            }
           
            connect(root.left);
            connect(root.right);
        }
    }

    层序遍历法:

    /*
    *利用层序遍历,每一层都将指针指向他的下一个结点,
    *这里用size标记每一层是否遍历完毕。
    *
    */
    public class Solution {
        public void connect(TreeLinkNode root) {
           if(root==null)return ;
            Queue<TreeLinkNode> q=new LinkedList();
            q.add(root);
            while(!q.isEmpty()){
                int size=q.size();
                for(int i=0;i<size;i++){
                    TreeLinkNode temp=q.peek();q.poll();
                    if(i<size-1)temp.next=q.peek();
                    if(temp.left!=null)q.add(temp.left);
                    if(temp.right!=null)q.add(temp.right);
                }
            }
        }
    }

    最巧妙地:利用层指针和深度的指针

    public class Solution {
        public void connect(TreeLinkNode root) {
            if(root==null)return ;
            TreeLinkNode cur=null,start=root;
            while(start.left!=null){
                cur=start;
                while(cur!=null){
                    cur.left.next=cur.right;
                   if(cur.next!=null)cur.right.next=cur.next.left;
                    cur=cur.next;
                }
                start=start.left;           //这个地方是left,不是next
            }
        }
    }
  • 相关阅读:
    __file__ 作用以及模块导入方法
    random 模块
    time 模块
    module模块和包
    装饰器
    python闭包
    filter map reduce函数的使用
    python文件处理
    python内置函数使用
    函数
  • 原文地址:https://www.cnblogs.com/patatoforsyj/p/9538312.html
Copyright © 2011-2022 走看看