java算法联系,二叉树遍历

1.前序遍历二叉树

在这里插入代码片
/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */
 class Solution{
	public void preorderTraversal(TreeNode root){
		Stack<TreeNode> stack = new Stack<TreeNode>();
		ArrayList <Integer> list = new ArrayList<Integer>();
		if(root != null){
			stack.push(root);
			while(!stack.isEmpty()){
				TreeNode treeNode = stack.pop();
				list.add(treeNode.val);
				if(treeNode.right != null){
					stack.push(treeNode.right);
				}
				if(treeNode.left != null){
					stack.push(treeNode.left);
				}
			}
		}	
	}
}

先序先根,接着左,接着右。程序中很好的体现了,先处理了根节点,接着因为栈先进后出特点,先让右进去,接着进左,方便先处理左节点,接着处理右节点。

2.中序遍历

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */
 class Solution{
	public void inorderTraversal(TreeNode root){
		public ArrayList<Integer> inOrder(TreeNode treeNode, ArrayList<Integer> list){
			if(treeNode == null) return null;
			inOrder(treeNode.left, list);
			list.add(treeNode.val);
			inOrder(treeNode.right,list);
			return list;
		}
	}

左中右

你可能感兴趣的:(java,算法,java,算法,开发语言)