Leetcode 1305. All Elements in Two Binary Search Trees
题目链接: All Elements in Two Binary Search Trees
难度:Medium
题目大意:
将两棵整数型二叉树上的节点按升序进行排序。
思路:
思路:
分别遍历两棵二叉树,将节点读取到List中,再对List进行排序。
代码
思路:
/*** 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> getAllElements(TreeNode root1, TreeNode root2) {List<Integer> ans=new ArrayList<Integer>();inorder(root1,ans);inorder(root2,ans);Collections.sort(ans);return ans;}private void inorder(TreeNode root,List<Integer> list){if(root==null){//将二叉树的各个节点存在List中return;}list.add(root.val);inorder(root.left,list);inorder(root.right,list);}
}