Binary Tree Preorder Traversal 두 갈래 나무의 순서 @LeetCode

2474 단어
귀속과 교체로 Pre-Order의 고전을 구하려면 언제 In-Order,Post-Order,Level-Order의 반복을 한 번 써야 합니까? 너무 고전적이기 때문에 직접 외우는 것이 가장 좋습니다.
package Level3;

import java.util.ArrayList;
import java.util.Stack;

/**
 *  Binary Tree Preorder Traversal
 *  
 *  Given a binary tree, return the preorder traversal of its nodes' values.

For example:
Given binary tree {1,#,2,3},
   1
    \
     2
    /
   3
return [1,2,3].

Note: Recursive solution is trivial, could you do it iteratively?
 */
import Utility.TreeNode;

public class S128 {

	public static void main(String[] args) {
		TreeNode root = new TreeNode(1);
		TreeNode n1 = new TreeNode(2);
		root.right = n1;
		System.out.println(preorderTraversal(root));
		System.out.println(iter(root));
	}
	
	public static ArrayList<Integer> preorderTraversal(TreeNode root) {
		ArrayList<Integer> ret = new ArrayList<Integer>();
		rec(root, ret);
        return ret;
    }

	public static void rec(TreeNode root, ArrayList<Integer> ret){
		if(root == null){
			return;
		}
		
		ret.add(root.val);
		rec(root.left, ret);
		rec(root.right, ret);
	}
	
	//  
	public static ArrayList<Integer> iter(TreeNode root) {
		ArrayList<Integer> ret = new ArrayList<Integer>();
		Stack<TreeNode> stack = new Stack<TreeNode>();
		
		if(root == null){
			return ret;
		}
		
		stack.push(root);
		TreeNode cur = null;
		while(!stack.isEmpty()){
			cur = stack.peek();		//  
			ret.add(cur.val);
			stack.pop();
			
			//  , pop pop pop 
			if(cur.right != null){
				stack.push(cur.right);
			}
			if(cur.left != null){
				stack.push(cur.left);
			}
		}
		
		return ret;
	}
	
}
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ArrayList<Integer> preorderTraversal(TreeNode root) {
        ArrayList<Integer> ret = new ArrayList<Integer>();
        if(root == null){
            return ret;
        }
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode cur = stack.pop();
            ret.add(cur.val);
            if(cur.right != null)
            	stack.push(cur.right);
            if(cur.left != null)
            	stack.push(cur.left);
        }
        return ret;
    }
}

좋은 웹페이지 즐겨찾기