描述:
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
思路:
就是用两个list存储相邻两层的结点,把第i+1层结点存储到list中的同时,分别将第i层的各个节点指向下一个,跟116题Populating Next Right Pointers in Each Node I一个思路,就不重复写了。
代码:
/** * 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) { if(root==null) return ; List<TreeLinkNode>list=new ArrayList<TreeLinkNode>(); List<TreeLinkNode>temp=new ArrayList<TreeLinkNode>(); TreeLinkNode node=null,tempNode=null; list.add(root); while(true) { tempNode=list.get(0); if(tempNode.left!=null) temp.add(tempNode.left); if(tempNode.right!=null) temp.add(tempNode.right); for(int i=1;i<list.size();i++) { node=list.get(i); if(node.left!=null) temp.add(node.left); if(node.right!=null) temp.add(node.right); tempNode.next=node; tempNode=node; } if(temp.size()!=0) { list=temp; temp=new ArrayList<TreeLinkNode>(); } else break; } return; } }
结果:
时间: 2024-10-06 17:54:37