算法:二叉树的后序遍历算法分享

//1.递归
	public List postorderTraversal(TreeNode root) {
		List list = new ArrayList<>();
		postorder_Traversal(root, list);
		return list;
    }
	
	public void postorder_Traversal(TreeNode root,List list){
		if (root == null) return;
		postorder_Traversal(root.left, list);
		postorder_Traversal(root.right, list);
		list.add(root.val);
	}
	
//2.迭代
	public List postorderTraversal(TreeNode root) {
		List list = new ArrayList<>();
		Stack stack = new Stack<>();
		TreeNode node = root;
		TreeNode oldNode = root;//记录上一次访问的节点
		
		stack.push(node);
		while(!stack.isEmpty()) {
			TreeNode top = stack.peek();//如果栈顶节点是叶子节点,或者上次访问节点是栈顶节点的子节点,则弹出栈顶节点,进行访问。
			if ((top.left == null && top.right == null) || (top.left == oldNode || top.right == oldNode)) {
				node = stack.pop();
				list.add(node.val);
				oldNode = node;
			}else {
				if (top.right != null) stack.push(top.right);
				if (top.left != null) stack.push(top.left);
			}
		}
		return list;
	}

 

你可能感兴趣的:(算法:二叉树的后序遍历算法分享)