Object.clone()
Object类的clone()方法,创建和返回该对象的一个拷贝
protected native Object clone() throws CloneNotSupportedException;
It creates a new instance of the class of current object and initializes all its fields with exactly the contents of the corresponding fields of this object.
对象的克隆会创建当前对象类的一个实例,并初始化所有的域,初始化的值与当前对象的域的值一模一样
如何用clone()获得一个对象的副本
克隆一个对象,该对象类或其父类必须有一个公共的clone()方法
@Override public Object clone() throws CloneNotSupportedException { return super.clone(); }
1. 每一个实现了clone()方法的类必须调用super.clone()以获得克隆对象的引用
2. 该类必须实现了java.lang.Cloneable接口
浅拷贝 vs 深拷贝
浅拷贝(Shallow Copy):对象和拷贝对象引用类型的字段会指向同一块区域,因此两个对象引用类型的字段改变都会影响另一个对象。
深拷贝(Deep Copy)
二叉树的先序遍历
先序遍历:根节点->左子树->右子树
题目:通过先序遍历返回一个二叉树节点的值(https://leetcode.com/explore/learn/card/data-structure-tree/134/traverse-a-tree/928/)
如:
代码参考:
public List<Integer> preorderTraversal(TreeNode node) { List<Integer> list = new LinkedList<Integer>(); Stack<TreeNode> rights = new Stack<TreeNode>(); while(node != null) { list.add(node.val); if (node.right != null) { rights.push(node.right); } node = node.left; if (node == null && !rights.isEmpty()) { node = rights.pop(); } } return list; }