classSolution{public:vector<int>boundaryOfBinaryTree(TreeNode*root){if(root==nullptr)return{};vector<int>ans{root->val};dfs(root->left,true,false,ans);dfs(root->right,false,true,ans);returnans;}private:/** * 1. root->left is left boundary if root is left boundary * root->right if left boundary if root->left == nullptr * 2. same applys for right boundary * 3. if root is left boundary, add it before 2 children - preorder * if root is right boundary, add it after 2 children - postorder * 4. a leaf that is neighter left/right boundary belongs to the bottom */voiddfs(TreeNode*root,boollb,boolrb,vector<int>&ans){if(root==nullptr)return;if(lb)ans.push_back(root->val);if(!lb&&!rb&&root->left==nullptr&&root->right!=nullptr)ans.push_back(root->val);dfs(root->left,lb,rb&&root->right==nullptr,ans);dfs(root->right,lb&&root->left==nullptr,rb,ans);if(rb)ans.push_back(root->val);}};
classSolution{publicList<Integer>boundaryOfBinaryTree(TreeNoderoot){if(root==null)returnnewArrayList<>();List<Integer>ans=newArrayList<>(Arrays.asList(root.val));dfs(root.left,true,false,ans);dfs(root.right,false,true,ans);returnans;}/** * 1. root.left is left boundary if root is left boundary * root.right if left boundary if root.left == null * 2. same applys for right boundary * 3. if root is left boundary, add it before 2 children - preorder * if root is right boundary, add it after 2 children - postorder * 4. a leaf that is neighter left/right boundary belongs to the bottom */privatevoiddfs(TreeNoderoot,booleanlb,booleanrb,List<Integer>ans){if(root==null)return;if(lb)ans.add(root.val);if(!lb&&!rb&&root.left==null&&root.right==null)ans.add(root.val);dfs(root.left,lb,rb&&root.right==null,ans);dfs(root.right,lb&&root.left==null,rb,ans);if(rb)ans.add(root.val);}}
classSolution:defboundaryOfBinaryTree(self,root:Optional[TreeNode])->List[int]:ifnotroot:return[]ans=[root.val]defdfs(root:Optional[TreeNode],lb:bool,rb:bool):""" 1. root.left is left boundary if root is left boundary root.right if left boundary if root.left is None 2. same applys for right boundary 3. if root is left boundary, add it before 2 children - preorder if root is right boundary, add it after 2 children - postorder 4. a leaf that is neighter left/right boundary belongs to the bottom """ifnotroot:returniflb:ans.append(root.val)ifnotlbandnotrbandnotroot.leftandnotroot.right:ans.append(root.val)dfs(root.left,lb,rbandnotroot.right)dfs(root.right,lbandnotroot.left,rb)ifrb:ans.append(root.val)dfs(root.left,True,False)dfs(root.right,False,True)returnans