/** * 递归实现前序遍历 * 中-左-右 * @param node TreeNode * @return List */ publicstatic List rootLeftRightRecursive(TreeNode node){ if (null != node){ list.add(node.val); rootLeftRightRecursive(node.left); rootLeftRightRecursive(node.right); } return list; }
/** * 非递归实现前序遍历 * 中-左-右 * @param node TreeNode * @return List */ publicstatic List rootLeftRightNonRecursive(TreeNode node){ Stack<TreeNode> stack = new Stack<>(); TreeNode cur = node;
while (null != cur || !stack.isEmpty()) { if (null != cur) { list.add(cur.val); stack.push(cur); cur = cur.left;
} else { cur = stack.pop(); cur = cur.right; } } return list; }
/** * 递归实现中序遍历 * 左-中-右 * @param node TreeNode * @return List */ publicstatic List leftRootRightRecursive(TreeNode node){ if (null!=node){ leftRootRightRecursive(node.left); list.add(node.val); leftRootRightRecursive(node.right); } return list; }
/** * 非递归实现中序遍历 * 左-中-右 * @param node TreeNode * @return List */ publicstatic List leftRootRightNonRecursive(TreeNode node){ List<Integer> list = new ArrayList<>(10); Stack<TreeNode> stack = new Stack<>(); TreeNode cur = node;
while (null != cur || !stack.isEmpty()) { if (null != cur) { stack.push(cur); cur = cur.left; } else { cur = stack.pop(); list.add(cur.val); cur = cur.right; } }
return list; }
/** * 递归实现后序遍历 * 左-右-中 * @param node TreeNode * @return List */ publicstatic List leftRightRootRecursive(TreeNode node){
if (null!=node){ leftRightRootRecursive(node.left); leftRightRootRecursive(node.right); list.add(node.val); } return list; }
/** * 非递归实现后序遍历 * 左-右-中 * @param node TreeNode * @return List */ publicstatic List leftRightRootNonRecursive(TreeNode node){ if (null == node){ return list; } Stack<TreeNode> stack = new Stack<>(); stack.push(node); TreeNode cur;
while (!stack.isEmpty()){ cur = stack.pop(); if (cur.left!=null){ stack.push(cur.left); } if (cur.right!=null){ stack.push(cur.right); } // 逆序添加 list.add(0,cur.val); } return list; }
/** * 层序遍历队列实现(广度优先算法BFS) * @param root TreeNode * @return List */ publicstatic List<List<Integer>> levelOrder(TreeNode root){ List<List<Integer>> list = new ArrayList<>(); if(root == null){ return list; }
Queue<TreeNode> queue = new LinkedList<>(); queue.add(root);
/** * 递归实现获取树的深度 * @param node TreeNode * @return int */ publicstaticintdepth(TreeNode node){ if (node == null){ return0; } int left = depth(node.left); int right = depth(node.right);