zoukankan      html  css  js  c++  java
  • [leetcode]Populating Next Right Pointers in Each Node II

    这道题目由于之前那题的训练,思路来的很快,但写的时候脑子浆糊了。这个时候就要高屋建瓴的去思考,把其中一段循环什么啊提炼成一个函数出来,那么主要那一块的逻辑就简单了。

    public class Solution {
        public void connect(TreeLinkNode root) {
            if (root != null) root.next = null;
            TreeLinkNode first = root;
            TreeLinkNode last = null;
            while (first != null)
            {
                TreeLinkNode n = first;
                while (n != null)
                {
                    if (n.left != null)
                    {
                        if (last != null) last.next = n.left;
                        last = n.left;
                    }
                    if (n.right != null)
                    {
                        if (last != null) last.next = n.right;
                        last = n.right;
                    }
                    n = n.next;
                }
                first = getNextLevelFirst(first);
                last = null;
            }
        }
        
        private TreeLinkNode getNextLevelFirst(TreeLinkNode first)
        {
            if (first == null) return null;
            while (first.left == null && first.right == null && first.next != null)
            {
                first = first.next;
            }
            if (first.left == null && first.right == null)
            {
                return null;
            }
            else if (first.left != null)
            {
                return first.left;
            }
            else if (first.right != null)
            {
                return first.right;
            }
            return null;
        }
    }
    

      

  • 相关阅读:
    UltraSoft
    UltraSoft
    UltraSoft
    UltraSoft
    UltraSoft
    2020软工提问回顾与个人总结作业
    2020软工结对项目作业-简单几何形状间交点统计
    2020软工个人博客作业-博客园班级博客分析
    2020软工个人阅读博客作业
    2020软工第一次作业-热身
  • 原文地址:https://www.cnblogs.com/lautsie/p/3298919.html
Copyright © 2011-2022 走看看