非递归前序排列代码/** Inorder traversal from the root*/
public void nonRecursivePreorder() {
java.util.ArrayList list = new java.util.ArrayList();
MyStack stack = new MyStack(); if (root == null) return; stack.push(root); while (!stack.isEmpty()) { //这段无法理解
TreeNode node = (TreeNode)(stack.peek());
stack.pop(); // Remove the node from the stack
list.add(node);
if (node.right != null && !list.contains(node.right)) { // 为什么这么写
stack.push(node.right); // Add the right node to the stack
}
if (node.left != null && !list.contains(node.left)) {
stack.push(node.left); // Add the left node to the stack
}
} for (int i = 0; i < list.size(); i++)
System.out.print(((TreeNode)(list.get(i))).element + " ");
}递归的代码 private void preorder(TreeNode root) {
if (root == null) {
return;
}
System.out.print(root.element + " ");
preorder(root.left);
preorder(root.right);
}求指导,栈的操作过程是怎么样的
public void nonRecursivePreorder() {
java.util.ArrayList list = new java.util.ArrayList();
MyStack stack = new MyStack(); if (root == null) return; stack.push(root); while (!stack.isEmpty()) { //这段无法理解
TreeNode node = (TreeNode)(stack.peek());
stack.pop(); // Remove the node from the stack
list.add(node);
if (node.right != null && !list.contains(node.right)) { // 为什么这么写
stack.push(node.right); // Add the right node to the stack
}
if (node.left != null && !list.contains(node.left)) {
stack.push(node.left); // Add the left node to the stack
}
} for (int i = 0; i < list.size(); i++)
System.out.print(((TreeNode)(list.get(i))).element + " ");
}递归的代码 private void preorder(TreeNode root) {
if (root == null) {
return;
}
System.out.print(root.element + " ");
preorder(root.left);
preorder(root.right);
}求指导,栈的操作过程是怎么样的
解决方案 »
- 菜鸟来了请高手帮帮我
- JOptionPane.showMessageDialog()对于参数(null,boolean)不适用?
- 急!急!急!用jxl修改了excel表后,不能再次读取
- 怎样监听窗口
- Java中StringTokenizer分隔符可以是正则表达式吗
- 这个问题比较简单,但我是新手,不能解决,我会给100分来回报大家,万分火急。
- 什么是内置类型,请给出详细的定义,谢谢
- jbuilder中利用junit做单元测试时配置数据库的问题
- 诸位大虾,小弟无法继续学了,请指教,狂给分!!!!!!!!!!!!
- 如何运行打好的JAR包?点击行吗?
- socket接受的对象是否能用字符流接受?
- 求一个java绘图程序,高手进!!必有重谢!!
/** Inorder traversal from the root*/
public void nonRecursivePreorder() {
java.util.ArrayList list = new java.util.ArrayList();
MyStack stack = new MyStack(); if (root == null) return; stack.push(root); while (!stack.isEmpty()) {
//因为先序是根左右,所以不为空则弹出根节点
TreeNode node = (TreeNode)(stack.peek());
stack.pop(); // Remove the node from the stack
list.add(node);
if (node.right != null && !list.contains(node.right)) {
stack.push(node.right); // 有右节点则将右节点压栈
}
if (node.left != null && !list.contains(node.left)) {
stack.push(node.left); // 有左节点则将左节点压栈,因为栈是后进先出,所以这个左子节点会
//在下一次循环当做根节点出栈
}
}//也许是我语言匮乏,不知道该怎么解释了,这段程序基本很难再清晰了 for (int i = 0; i < list.size(); i++)
System.out.print(((TreeNode)(list.get(i))).element + " ");
}