Python的變數,常量,資料型別與註釋
阿新 • • 發佈:2022-03-03
1、先序遍歷
class Solution { public List<Integer> preorderTraversal(TreeNode root) { if(root == null) return new ArrayList<>(); Stack<TreeNode> stack = new Stack<>(); List<Integer> list = new ArrayList<>(); stack.push(root); //把頭節點入棧 while(!stack.isEmpty()){ TreeNode cur = stack.pop();//1、每次從棧中彈出一個節點 list.add(cur.val);//2、處理cur if(cur.right != null){//3、如果有右節點,入棧 stack.push(cur.right); } if(cur.left != null){ stack.push(cur.left);//4、如果有左節點,入棧 } } return list; } }
2、中序遍歷
class Solution { public List<Integer> inorderTraversal(TreeNode root) { if(root == null) return new ArrayList<>(); Stack<TreeNode> stack = new Stack<>(); List<Integer> list = new ArrayList<>(); while(!stack.isEmpty() || root != null){ if(root != null){ stack.push(root); root = root.left; }else{ root = stack.pop(); list.add(root.val); root = root.right; } } return list; } }
3、後序遍歷
class Solution { public List<Integer> postorderTraversal(TreeNode root) { if(root == null) return new ArrayList<>(); //可以在前序版本上修改,新增一個輔助棧 Stack<TreeNode> stack = new Stack<>(); Stack<Integer> assist = new Stack<>(); List<Integer> list = new ArrayList<>(); stack.push(root); while(!stack.isEmpty()){ TreeNode cur = stack.pop();//每次從棧中彈出一個節點 assist.push(cur.val);//2、處理cur,把其值壓入輔助棧 if(cur.left != null){ stack.push(cur.left);//3、如果有左節點,入棧 } if(cur.right != null){//4、如果有右節點,入棧 stack.push(cur.right); } } //讀出輔助棧內容 while(!assist.isEmpty()){ list.add(assist.pop()); } return list; } }