常见算法 - 二叉树:二叉树的遍历(递归与非递归)

二叉树的前序、中序、后序遍历:

递归实现:不同顺序改变递归就行。

前序:        

class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        
        List<Integer> list = new ArrayList<Integer>();
        if(root == null){
            return list; 
        }else{
            list.add(root.val);
            list.addAll(preorderTraversal(root.left));
            list.addAll(preorderTraversal(root.right));
            
        }
        return list;
       }
}            

非递归实现:即用栈模拟系统递归的实现,为了更方便理解,将节点信息封装一下,这样完全模拟系统递归了,其他顺序也只需要像递归实现一样改变顺序就好了。这里不同与书本的每种顺序各有个的非递归实现。

//非递归遍历二叉树,用stack模拟系统栈,根据递归思路实现,前中后一样。
public class L144BTreeTravesal {

	public  static List<Integer> preorderTraversal(TreeNode root) {		
		List<Integer> list = new ArrayList<Integer>();
		Stack<Command> stack = new Stack<Command>();
		if(root == null){
			return list;
		}
		stack.push(new Command(false, root));
		while(!stack.isEmpty()){
			
			Command curr = stack.pop();
			if(curr.isOut){
				list.add(curr.node.val);
			}else{
				if(curr.node.right != null){
					stack.push(new Command(false,curr.node.right));
				}
				if(curr.node.left != null){
					stack.push(new Command(false,curr.node.left));
				}
				stack.push(new Command(true, curr.node));
			}
		}	
		return list;
	}
}

class Command{
	boolean isOut;
	TreeNode node;
	public Command(boolean isOut, TreeNode node) {
		this.isOut = isOut;
		this.node = node;
	}
}


猜你喜欢

转载自blog.csdn.net/b9x__/article/details/80224817