public ListpreorderTraversal(TreeNode root) {//前序 List result = new ArrayList<>(); Stack tmp = new Stack<>(); if(root != null) tmp.push(root); TreeNode cur = null; while(!tmp.isEmpty()){ cur = tmp.pop(); if(cur!=null){ if(cur.right!=null) tmp.push(cur.right); if(cur.left!=null) tmp.push(cur.left); tmp.push(cur); tmp.push(null); // 中节点访问过,但是还没有处理,加入空节点做为标记。 } else{// 只有遇到空节点的时候,才将下一个节点放进结果集 cur = tmp.pop();// 重新取出栈中元素 result.add(cur.val); } } return result; }
public ListpreorderTraversal(TreeNode root) { //中序 List result = new ArrayList<>(); Stack tmp = new Stack<>(); if(root != null) tmp.push(root); TreeNode cur = null; while(!tmp.isEmpty()){ cur = tmp.pop(); if(cur!=null){ if(cur.right!=null) tmp.push(cur.right); tmp.push(cur); tmp.push(null); if(cur.left!=null) tmp.push(cur.left); } else{ cur = tmp.pop(); result.add(cur.val); } } return result; }
public ListpreorderTraversal(TreeNode root) { //后序 List result = new ArrayList<>(); Stack tmp = new Stack<>(); if(root != null) tmp.push(root); TreeNode cur = null; while(!tmp.isEmpty()){ cur = tmp.pop(); if(cur!=null){ tmp.push(cur); tmp.push(null); if(cur.right!=null) tmp.push(cur.right); if(cur.left!=null) tmp.push(cur.left); } else{ cur = tmp.pop(); result.add(cur.val); } } return result; }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)