二叉樹的中序遍歷
給定一個二叉樹的根節點 root ,回傳它的 中序 遍歷,
示例 1:
輸入:root = [1,null,2,3]
輸出:[1,3,2]
示例 2:
輸入:root = []
輸出:[]
示例 3:
輸入:root = [1]
輸出:[1]
示例 4:
輸入:root = [1,2]
輸出:[2,1]
示例 5:
輸入:root = [1,null,2]
輸出:[1,2]
提示:
樹中節點數目在范圍 [0, 100] 內
-100 <= Node.val <= 100
進階: 遞回演算法很簡單,你可以通過迭代演算法完成嗎?
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root){
List<Integer> res=new ArrayList<>();
inorder(root,res);
return res;
}
public void inorder(TreeNode root, List<Integer> res){
if (root==null){
return;
}
inorder(root.left,res);
res.add(root.val);
inorder(root.right,res);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/339060.html
標籤:其他
